简体   繁体   中英

My ajax/jquery function doesnt apply to dynamically loaded in pagination content

I remember having this problem once before but I dont know which project it was on or how I fixed it.

I have an ajax 'add to favorite' button, and I also have infinite scroll which ajax loads pages when you reach the bottom of the page. The problem is the ajax doesnt apply to the newly appended content

// Favorites
  $('.res-list .star').click(function(){
    var starLink = $(this);
    var listItem = $(this).parent().parent();

    if ($(starLink).hasClass('starred')) {
       $(starLink).removeClass('starred');
     } else {
       $(starLink).addClass('starred');
     }
     $.ajax({
       url: '/favorites/?id=' + $(starLink).attr('data-id'),
       type: 'PUT',
       success: function() {

         if ($(starLink).hasClass('starred')) {
           $(listItem).animate({
             backgroundColor: '#FFF8E4'
           }, 400);
         } else {
           $(listItem).animate({
             backgroundColor: '#ffffff'
           }, 400);
         }
       }
     });
     return false;
  });

You need live event

$('.res-list').on('click', '.star', function() {

   // code here
});

or use delegate()

$('.res-list').delegate('.star', 'click', function() {

       // code here
    });

read about delegate()

read about on()

The .bind() method will attach the event handler to all of the anchors that are matched! That is not good. Not only is that expensive to implicitly iterate over all of those items to attach an event handler, but it is also wasteful since it is the same event handler over and over again.

The .delegate() method behaves in a similar fashion to the .live() method, but instead of attaching the selector/event information to the document, you can choose where it is anchored. Just like the .live() method, this technique uses event delegation to work correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM