编程语言
首页 > 编程语言> > javascript – 无法理解addEventListener中的useCapture参数

javascript – 无法理解addEventListener中的useCapture参数

作者:互联网

我在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,child div有usecapture设置为false,文件usecapture被跟随.所以为什么document属性比child更受欢迎.

function load() {
  document.addEventListener("click", function() {
    alert("parent event");
  }, true);

  document.getElementById("div1").addEventListener("click", function() {
    alert("child event");
  }, false);
}
<body onl oad="load()">
  <div id="div1">click me</div>
</body>

解决方法:

事件可以在两种情况下激活:开始(“捕获”)和结束(“泡沫”).
     
事件按照它们的定义顺序执行.比如说,你定义了4个事件监听器:

window.addEventListener("click", function(){alert(1)}, false);
window.addEventListener("click", function(){alert(2)}, true);
window.addEventListener("click", function(){alert(3)}, false);
window.addEventListener("click", function(){alert(4)}, true);

警报框将按以下顺序弹出:

> 2(首先定义,使用capture = true)
> 4(使用capture = true定义第二个)
> 1(第一个定义的事件,capture = false)
> 3(第二个定义的事件,其中capture = false)

标签:javascript,dom,javascript-events,dom-events
来源: https://codeday.me/bug/20190916/1807136.html