简体   繁体   English

使用.on的附加内容的jQuery事件?

[英]jQuery events for appended content using .on?

I have appended content (using ajax) to my document and my events are not firing. 我已将内容(使用ajax)附加到我的文档中,并且我的事件未触发。 I know this can be done using .live() but I read somewhere that it's deprecated now? 我知道这可以使用.live()来完成,但我在某处读到它现在已被弃用了?

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. 通过这种方式,您可以将事件处理委托给加载DOM时存在的ul,并处理通过AJAX添加的元素的事件。 If the ul is not present when the dom is loaded you could delegate to the <body> tag 如果在加载dom时不存在ul,则可以委托<body>标记

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. 编辑 - live()它实际上是on()的包装(在它是delegate()的包装之前),但通常将事件处理委托给window ,这意味着事件必须冒出很多。 Taken from jQuery source 取自jQuery源码

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. 因此,您将事件追加到某个父元素,该元素查找页面加载时存在的兄弟元素,以及将来添加的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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