Why do my Jquery events stop working after an AJAX request?

Asked

Viewed 330 times

2

I have two buttons that when clicked make the call of a .on('click',function()) but before that an AJAX request is made and after that request they no longer work. Before I did the function to perform the request it worked perfectly. That’s the request:

$.ajax({
     url: "teste.php",
     type: 'GET',
     success: function(html){
         var headline = $(html).find('#teste');                                                     
         $('#teste').html(headline);
     }   
 });

and the button with the .on('click') that’s the one:

$('.remove-item').on('click',function(){alert('teste')});

2 answers

6


When the element is inserted in the DOM via javascript it is necessary to inform the selector of the same of it.

Example:

$('body').on('click', '.remove-item', function(){alert('teste')});

3

Because it is a dynamic request (coming from the DOM) it is necessary to inform the class where it is inside, as the example below:

$('.minhaClasse').on('click', '.classeInterna', function() {
    alert('minha classe interna')
});

Otherwise it will not work, or if you have more than one class, you may get the last class presented. An example with more classes (for example a for):

$('.minhaClasse').on('click', '.classeInterna', function() {
    var minhaImg = $(this).attr('src'); 
    console.log(minhImg); 
});

Take the path of the image clicked on this example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.