JQuery切换应用程序从“live”到“on”方法

可能重复:
jQuery 1.7 – 将live()转换为on()

只需将我的代码从“live”切换到“on”,有些事件就不再激活了,这里有一个例子,任何人都可以帮忙说出它有什么问题吗? 它之前使用“live”而不是“on”方法100%正确工作….

$('a#doBulkLink').on('click', function (e) { createLabelsWithDestinationFolders(); $('label.moveDocDestinationFolder').on('click', function (e) { doSomeAjaxStuffWithLabels(); e.stopImmediatePropagation(); }); e.preventDefault(); }); 

谢谢。

只需将函数名称更改为on()就不能用on()替换live() on() ; 签名也会发生变化。

 $('selector').live('event', function () { }); 

……变得……

 $(document).on('event', 'selector', function () { }); 

在它的当前forms中,你拥有的是bind()的直接替代品(其中click()change()等是别名)。 因此,处理程序直接绑定到元素,而不是将处理程序绑定到document并利用事件冒泡,这就是live()所做的。

要以与live()相同的方式使用on() ,请执行以下操作:

 $(document).on('click', 'a#doBulkLink', function() { } ); 

正如文档中所示: http : //api.jquery.com/live/

如果a#doBulkLink动态插入到dom中,则定义.on的方式将不起作用,

尝试,

 //replace document with any closest container of 'a#doBulkLink' which is available //in dom when this code is executed. $(document).on ('click', 'a#doBulkLink', function () { createLabelsWithDestinationFolders(); $('label.moveDocDestinationFolder').on('click', function (e) { doSomeAjaxStuffWithLabels(); e.stopImmediatePropagation(); }); e.preventDefault(); }); 

我搞定了,固定!!!!,我犯了两个愚蠢的错误:

  • 第一个事件(在#doBulkLink上)不是动态的(它存在于页面上存在的隐藏元素上,#s欺骗了我!)
  • 在第二个事件中(在label.moveDocDestinationFolder上)我在我的JQuery“.on”方法语法中使用了$('document')而不是$(document)

所以代码看起来像这样,并且100%正常工作:

 // this is not dynamically added element, but still can use ".on" to attach an event to // outer div and delegate to a#doBulkLink when clicked $('div#doBulkLinkBox').on('click', 'a#doBulkLink' ,function (e) { createLabelsWithDestinationFolders(); // these are dynamic elements so let's use "on" to attach a click event $(document).on('click', 'label.moveDocDestinationFolder', function (e) { doSomeAjaxFunkWithLabels(); e.stopImmediatePropagation(); }); e.preventDefault(); }); 

感谢大家提示!