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

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 do not work anymore. Before I did the function to make the request, it worked perfectly. This is the requisition:

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

and the button with .on('click') is this:

$('.remove-item').on('click',function(){alert('teste')});
    
asked by anonymous 25.11.2015 / 17:33

2 answers

6
  

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

Example:

$('body').on('click', '.remove-item', function(){alert('teste')});
    
25.11.2015 / 17:36
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 it has more than one class, it might take 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); 
});

Get the path of the img clicked in this example.

    
25.11.2015 / 17:44