简体   繁体   中英

jQuery events for appended content using .on?

I have appended content (using ajax) to my document and my events are not firing. I know this can be done using .live() but I read somewhere that it's deprecated now?

This is my code (it works fine on document ready, but not on the newly appended items):

$('li[id^="inv-"] a.close').on('click', function(){
 var item=($(this).closest("li[id^='inv-']")).attr('id');
 var id = parseInt(item.replace("inv-", ""));
 $.ajax({
   type: "POST",
   url: "ajax-invi.php",
   dataType: "html",
   data: "id="+idboda+"&idinv="+id+"&borrar=ok",
   success: function(data) {
     noty({"text":"El invitado ha sido borrado"});
     $("body").find('li#inv-' + id).remove();
   }
  }); 
});

And the items:

<ul>
  <li id="inv-39">
   <div class="row_field">
     <label>Adri</label>
     <a class="close" href="#invlist">Borrar</a>
   </div>                  
  </li>
  <li id="inv-40">
   <div class="row_field">
     <label>Marga</label>
     <a class="close" href="#invlist">Borrar</a>
   </div>  
  </li>
</ul>                

try

$('ul').on('click','a.close', function(){
 var item=($(this).closest("li[id^='inv-']")).attr('id');
 var id = parseInt(item.replace("inv-", ""));
 $.ajax({
   type: "POST",
   url: "ajax-invi.php",
   dataType: "html",
   data: "id="+idboda+"&idinv="+id+"&borrar=ok",
   success: function(data) {
     noty({"text":"El invitado ha sido borrado"});
     $("body").find('li#inv-' + id).remove();
   }
  }); 
});

in this way you delegate the event handling to the ul which is present when the DOM is loaded and handles the events of elements added through AJAX. If the ul is not present when the dom is loaded you could delegate to the <body> tag

EDIT - live() it's actually a wrapper around on() (before it was a wrapper around delegate() ) but delegates the event handling usually to the window which means that the event has to bubble up a lot. Taken from jQuery source

live: function( types, data, fn ) {
    jQuery( this.context ).on( types, this.selector, data, fn );
    return this;
},
$(document).on('click', 'li[id^="inv-"] a.close', function(){ 
//... 
});

So, you append event to some parent element, which looks for siblings which exists on page-loading and which will be appended in future.

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