weixin_33725515 2015-11-18 19:58 采纳率: 0%
浏览 21

在ajax回调中创建链接

This question already has answers here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/203198/event-binding-on-dynamically-created-elements" dir="ltr">Event binding on dynamically created elements?</a>
                            <span class="question-originals-answer-count">
                                (23 answers)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2015-11-19 00:16:24Z" class="relativetime">4 years ago</span>.</div>
        </div>
    </aside>

I create a link in ajax callback function and define a class for that, commands that I write on click of this link doesn't work. the code is here:

$('.catpics').click(function(){
   var id=$(this).attr('id');
   $.post('storehouse.php', {
     catid:id,
     btn:'showsub'
   },function(data){
     $('#subcatshelf').append('<a class="catpics" id="'+ data+'">'+data+'</a>');
   });
</div>
  • 写回答

1条回答 默认 最新

  • weixin_33686714 2015-11-18 20:08
    关注

    $('.catpics').click(function(){ only binds to links once. You're looking for .on which will bind to the first object you give it (so you can give it the body of your webpage) and then tell it to listen for clicks on .catpics and since the listener is on the body and not the individual .catpics elements, it wont matter when the links are actually inserted or deleted:

    $('body').on('click', '.catpics', function() {
       var id=$(this).attr('id');
       $.post('storehouse.php', {catid:id,btn:'showsub'},function(data){
         $('#subcatshelf').append('<a class="catpics" id="'+ data+'">'+data+'</a>');
       });
    });
    

    alternatively you can make click work just fine by pulling out the event handler and just setting up a new clicked listener as you insert a new link:

    function clickedCatPic() {
       var id=$(this).attr('id');
       $.post('storehouse.php', {catid:id,btn:'showsub'},function(data){
         var link = $('<a class="catpics" id="'+ data+'">'+data+'</a>');
         $('#subcatshelf').append(link);
         link.click(clickedCatPic);
       });
    }
    
    $('.catpics').click(clickedCatPic);
    
    评论

报告相同问题?