我已在 https://developer.mozilla.org/en/DOM/element.addEventListener 阅读文章但无法理解 useCapture
属性。定义有:
If true, useCapture indicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered listener before being dispatched to any EventTargets beneath it in the DOM tree. Events which are bubbling upward through the tree will not trigger a listener designated to use capture.
在这段代码中,父事件在子事件之前触发,所以我无法理解它 behavior.Document 对象的 usecapture 为 true,子 div 的 usecapture 设置为 false,并且遵循 document usecapture。那么为什么 document 属性优于 child。
function load() {
document.addEventListener("click", function() {
alert("parent event");
}, true);
document.getElementById("div1").addEventListener("click", function() {
alert("child event");
}, false);
}
<body onload="load()">
<div id="div1">click me</div>
</body>
最佳答案
事件可以在两种情况下被激活:开始(“捕获”)和结束(“泡沫”)。 事件按照定义的顺序执行。比如说,你定义了 4 个事件监听器:
window.addEventListener("click", function(){console.log(1)}, false);
window.addEventListener("click", function(){console.log(2)}, true);
window.addEventListener("click", function(){console.log(3)}, false);
window.addEventListener("click", function(){console.log(4)}, true);
日志消息将按以下顺序显示:
2
(首先定义,使用capture=true
)4
(使用capture=true
定义第二个)1
(第一个使用capture=false
定义的事件)3
(第二个用capture=false
定义的事件)
关于javascript - 无法理解 addEventListener 中的 useCapture 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7398290/