gpt4 book ai didi

javascript - 在 Javascript 事件委托(delegate)中使用循环

转载 作者:行者123 更新时间:2023-11-30 05:40:57 25 4
gpt4 key购买 nike

我有以下代码:

var page = document.getElementById("contentWrapper");
page.addEventListener("click", function (e) {
var target, clickTarget, propagationFlag;
target = e.target || e.srcElement;
while (target !== page) {
clickTarget = target.getAttribute("data-clickTarget");
if (clickTarget) {
clickHandler[clickTarget](e);
propagationFlag = target.getAttribute("data-propagationFlag");
}
if (propagationFlag === "true") {
break;
}
target = target.parentNode;
}
});

我在整个项目(单页应用程序)中使用单个事件处理程序。事件处理程序使用属性“data-clickTarget”进行标识,并使用“data-propagationFlag”来防止事件传播。

如果 DOM 树很大,我应该使用循环方法还是传统的事件处理程序?

最佳答案

如果文档很大并且所选元素远离触发事件的元素,则委托(delegate)的事件处理程序可能会很慢......来自 JQuery 文档:

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.

正如文档所说的“点击”事件,这可能不会成为一个严重的问题(因为用户不会在页面上疯狂点击),但对于鼠标移动或滚动响应缓慢等事件可能会变得非常烦人.

委托(delegate)处理程序的具体特点是即使是后来添加到 DOM 的新元素也会使用处理程序,但你真的需要这个吗?如果您不是在编写一个库而只是一个应用程序,那么您可以控制何时添加新元素,因此您可以将偶数处理程序附件分解到元素创建中(换句话说,而不是拥有一个只创建新元素的函数,使以便它创建元素并自动注册标准事件处理程序)。

关于javascript - 在 Javascript 事件委托(delegate)中使用循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20866870/

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