Function javascript work with dynamically generated elements

0

How do I make this function work with dynamically generated elements? It works when element is loaded along with the page, but when I generate the div with ajax the function does not work!

$('.rating1').likeDislike({
        reverseMode: true,
        disabledClass: 'disable',
        click: function (value, l, d, event) {          
            var likes = $(this.element).find('.likes');
            var dislikes =  $(this.element).find('.dislikes');

            likes.text(parseInt(likes.text()) + l);
            dislikes.text(parseInt(dislikes.text()) + d);
        }     
    });

The ajax code:

$.ajax({
    url : link,
    type: 'GET',
    dataType: "html",
    preocessData: false,       
  })
  .done(function(msg2){  

     // Adiciono esse elemento dinamicamente
      <div class="rating rating1">
            <button class="btn btn-default like">Like</button>
            <span class="likes">0</span>
            <button class="btn btn-default dislike">Dislike</button>
            <span class="dislikes">0</span>
        </div>    
}

})
    
asked by anonymous 07.03.2018 / 17:01

1 answer

1

When you bind $('.rating1').likeDislike(.... it is applied only to elements that already exist in the DOM, you need to perform the same operation for those that are created dynamically after that. And I recommend you create them with a difernte class, novo , apply and then remove, so you avoid re-manipulating those that have already had the associated functionality.

There are more robust ways to solve this problem, but here is an example:

$.ajax({
    url : link,
    type: 'GET',
    dataType: "html",
    preocessData: false,       
  })
  .done(function(msg2){  

     // Adiciono esse elemento dinamicamente
      <div class="rating rating1 novoRating">
            <button class="btn btn-default like">Like</button>
            <span class="likes">0</span>
            <button class="btn btn-default dislike">Dislike</button>
            <span class="dislikes">0</span>
        </div>  

    //aplica aos novos elementos
    $('.novoRating').likeDislike({
        reverseMode: true,
        disabledClass: 'disable',
        click: function (value, l, d, event) {          
            var likes = $(this.element).find('.likes');
            var dislikes =  $(this.element).find('.dislikes');

            likes.text(parseInt(likes.text()) + l);
            dislikes.text(parseInt(dislikes.text()) + d);       

        }     
    });

    //remove a classe 
    $('.novoRating').removeClass('novoRating');
}

});
    
07.03.2018 / 17:58