gpt4 book ai didi

jquery - 在 jQuery 中监听文档级别的事件有什么缺点吗?

转载 作者:行者123 更新时间:2023-12-03 22:29:46 27 4
gpt4 key购买 nike

要监听元素上的事件,我认为要在文档级别监听:

$(document).on('click', '.myclass', function() {/*do something*/});

比元素级别监听的样式更好:

$('.myclass').on('click', function() { /*do something*/ }); 

原因是第一种样式也可以应用于动态添加的新元素。你还可以看到这种风格在 Bootstrap 中被大量使用:https://github.com/twitter/bootstrap/blob/master/js/bootstrap-alert.js

我想广泛使用第一种风格。但我想知道这种风格是否有任何缺点,比如性能?

最佳答案

来自可用的 jQuery 文档 here :

Event performance

In most cases, an event such as click occurs infrequently and performance is not a significant concern. However, high frequency events such as mousemove or scroll can fire dozens of times per second, and in those cases it becomes more important to use events judiciously. Performance can be increased by reducing the amount of work done in the handler itself, caching information needed by the handler rather than recalculating it, or by rate-limiting the number of actual page updates using setTimeout.

Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents.

jQuery can process simple selectors of the form tag#id.class very quickly when they are used to filter delegated events. So, "#myForm", "a.external", and "button" are all fast selectors. Delegated events that use more complex selectors, particularly hierarchical ones, can be several times slower--although they are still fast enough for most applications. Hierarchical selectors can often be avoided simply by attaching the handler to a more appropriate point in the document. For example, instead of $("body").on("click", "#commentForm .addNew", addComment) use $("#commentForm").on("click", ".addNew", addComment).

关于jquery - 在 jQuery 中监听文档级别的事件有什么缺点吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16383718/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com