让 jquery .on() 处理动态 html

发布于 2024-12-27 04:29:57 字数 379 浏览 2 评论 0原文

这在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最美的太阳 2025-01-03 04:29:57

新的 on 方法的工作方式与 delegate 在旧版本的 jQuery 中执行此操作。您需要在祖先元素上使用它并提供选择器。由于 DOM 事件从目标冒泡,它们最终将到达您使用 on 的祖先元素。当事件到达该元素时,将检查目标以查看它是否与您的选择器匹配。如果是这样,则执行事件处理程序:

$("#someAncestor").on("click", ".selector", function() {
    //Do stuff
});

自从版本 1.4 左右添加了 delegate 以来,就不再需要使用 live 了。使用 delegate ,上面的代码片段将是:

$("#someAncestor").delegate(".selector", "click", function() {
    //Do stuff
});

delegateonlive 效率更高,因为 live 始终将事件处理程序绑定到文档。这意味着必须测试页面上触发的每个事件,以查看它是否与选择器匹配,从而导致事件处理程序运行。使用 on 时,只有冒泡到祖先元素的事件才需要进行此检查。

The new on method works in much the same way that delegate 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 used on 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:

$("#someAncestor").on("click", ".selector", function() {
    //Do stuff
});

There has been no need to use live since delegate was added, some time around version 1.4. Using delegate the above snippet would be:

$("#someAncestor").delegate(".selector", "click", function() {
    //Do stuff
});

delegate and on are far more efficient than live, since live always binds event handlers to the document. 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. With on, only events that bubble to the ancestor element will require this check.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文