无法理解 addEventListener 中的 useCapture 参数 [英] Unable to understand useCapture parameter in addEventListener

查看:25
本文介绍了无法理解 addEventListener 中的 useCapture 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读 https://developer.mozilla.org/en/DOM 上的文章/element.addEventListener 但无法理解 useCapture 属性.定义有:

I have read article at https://developer.mozilla.org/en/DOM/element.addEventListener but unable to understand useCapture attribute. Definition there is:

如果为 true,则 useCapture 表示用户希望启动捕获.启动捕获后,指定类型的所有事件将被分派到注册的侦听器,然后再分派到 DOM 树中它下面的任何 EventTarget.通过树向上冒泡的事件不会触发指定使用捕获的侦听器.

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 并遵循文档 usecapture.所以为什么文档属性比 child 更受欢迎.

In this code parent event triggers before child,so I am not able to understand its behavior.Document object has usecapture true and child div has usecapture set false and document usecapture is followed.So why document property is preferred over 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 个事件侦听器:

Events can be activated at two occasions: At the beginning ("capture"), and at the end ("bubble"). Events are executed in the order of how they're defined. Say, you define 4 event listeners:

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);

日志消息将按以下顺序显示:

The log messages will appear in this order:

  • 2(首先定义,使用capture=true)
  • 4(使用 capture=true 定义第二个)
  • 1(第一个定义的事件,capture=false)
  • 3(第二个定义的事件,capture=false)
  • 2 (defined first, using capture=true)
  • 4 (defined second using capture=true)
  • 1 (first defined event with capture=false)
  • 3 (second defined event with capture=false)

这篇关于无法理解 addEventListener 中的 useCapture 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆