gpt4 book ai didi

jquery - 使用 jQuery 的 on() 函数的性能差异

转载 作者:行者123 更新时间:2023-12-01 06:45:31 25 4
gpt4 key购买 nike

我只是想知道哪种方式更有效,或者此操作的成本是否有任何差异:

    A) $(document).on('click', '#lol', function(){alert('hello')})

对比

    B) $('#lol').on('click', function(){alert('hello')})

我知道如果在执行ready函数后将ID为“lol”的元素附加到DOM中,后者将不起作用。我只是采用了到处使用实现 A 作为最佳实践,因为无论我的目标元素如何,它都会使所有事件代码保持相同。所以我想知道一直使用选项 A 是否有缺点?

最佳答案

是的,您不应尽可能使用 document,而应使用更接近目标的元素。

来自on() docs (强调我的):

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 - 使用 jQuery 的 on() 函数的性能差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29808079/

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