jQuery live() 事件处理程序的性能

发布于 2024-11-15 18:38:35 字数 289 浏览 0 评论 0原文

我正在考虑使用 live() 将事件处理程序绑定到我尚未插入 DOM 的函数。然而,这看起来很昂贵 - 每当插入元素或执行“单击”元素时,它都必须执行运行时检查,例如,查看是否应该调用处理程序。

在实践中这是值得担心的事情吗?还是 Javascript 现在太快了以至于不值得关心?

live() 函数的参考页面:http://api.jquery.com/直播/

I'm considering using live() to bind an event handler to a function I haven't inserted into the DOM. However this looks expensive - it must have to do a runtime check any time an element is inserted, or any time a "click" element is performed, for example, to see whether the handler should be called.

Is this something worth worrying about in practice, or is Javascript so fast now that this isn't worth caring about?

Reference page for the live() function: http://api.jquery.com/live/

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

笑梦风尘 2024-11-22 18:38:35

不,.live() 使用事件冒泡来完成它的任务。它只是附加到根元素并对通过 DOM 树冒泡的事件做出反应。它不会始终检查 DOM 元素。

从您链接到的页面:

.live() 方法能够通过使用事件委托影响尚未添加到 DOM 的元素:绑定到祖先元素的处理程序负责处理以下事件:触发其后代。传递给 .live() 的处理程序永远不会绑定到元素;相反,.live() 将一个特殊的处理程序绑定到 DOM 树的根。

继续阅读其中的更多细节。

No, .live() uses event bubbling to do its thing. It just attaches to the root element and reacts to events bubbling up through the DOM tree. It does not keep checking DOM elements all the time.

From the very page you link to:

The .live() method is able to affect elements that have not yet been added to the DOM through the use of event delegation: a handler bound to an ancestor element is responsible for events that are triggered on its descendants. The handler passed to .live() is never bound to an element; instead, .live() binds a special handler to the root of the DOM tree.

Keeping reading there as it goes into more detail.

你的往事 2024-11-22 18:38:35

您可能最好使用 delegate(),它不会将处理程序附加到文档上,而是附加到指定的父元素上。这意味着负载要少得多。在大多数情况下,建议使用它来代替 .live()

关于 Nettuts+ 上的差异< /a>

You might be better off using delegate(), which does not attach the handler on the document, but on a parent element specified. This means much less load. It is advised to use it instead of .live() in most situations.

About the differences on Nettuts+

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