让 jquery .on() 处理动态 html
这在 jQuery 1.6.4 中对于动态 html 工作得很好:
$(".selector").die().live("click", function () {
alert("clicked");
});
但我注意到在 jQuery 1.7.1 中 .live()
已被弃用并被 .on()
取代。如何将 .on()
与动态 html 一起使用?使用 .die().on("click", function())
不起作用,.off().on("click", function())
也不起作用代码>.
谢谢!
This works just fine in jQuery 1.6.4 for dynamic html:
$(".selector").die().live("click", function () {
alert("clicked");
});
but I noticed in jQuery 1.7.1 that .live()
is deprecated and replaced by .on()
. How can I use .on()
with dynamic html? Using .die().on("click", function())
doesn't work and neither does .off().on("click", function())
.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
新的
on
方法的工作方式与delegate
在旧版本的 jQuery 中执行此操作。您需要在祖先元素上使用它并提供选择器。由于 DOM 事件从目标冒泡,它们最终将到达您使用on
的祖先元素。当事件到达该元素时,将检查目标以查看它是否与您的选择器匹配。如果是这样,则执行事件处理程序:自从版本 1.4 左右添加了
delegate
以来,就不再需要使用live
了。使用delegate
,上面的代码片段将是:delegate
和on
比live
效率更高,因为live
始终将事件处理程序绑定到文档
。这意味着必须测试页面上触发的每个事件,以查看它是否与选择器匹配,从而导致事件处理程序运行。使用on
时,只有冒泡到祖先元素的事件才需要进行此检查。The new
on
method works in much the same way thatdelegate
did in older versions of jQuery. You need to use it on an ancestor element and supply a selector. Since DOM events bubble up from the target, they will eventually reach the ancestor element you have usedon
on. When the event reaches that element, the target is checked to see if it matches your selector. If so, the event handler is executed:There has been no need to use
live
sincedelegate
was added, some time around version 1.4. Usingdelegate
the above snippet would be:delegate
andon
are far more efficient thanlive
, sincelive
always binds event handlers to thedocument
. That means every single event triggered on the page has to be tested to see if it matches the selector and should therefore cause an event handler to run. Withon
, only events that bubble to the ancestor element will require this check.