gpt4 book ai didi

javascript - javascript中事件监听器的顺序是如何确定的?

转载 作者:行者123 更新时间:2023-11-29 19:11:32 24 4
gpt4 key购买 nike

假设有一个包含链接(一个 href)的 div,并且有三个事件监听器 - on-click- 1) 用于整个页面,2) 在 div 上 3) 一个标签。如果用户点击 a 标签,监听器是如何触发的?它们被注册的顺序是什么?

最佳答案

本质上,这取决于。事件有 2 个阶段,捕获(先发生),文档向下,冒泡,元素向上。

JS 可以做到这两点,这就是为什么在创建自定义事件监听时你有第三个 bool 变量,例如

parent.addEventListener('click',doSomething2,true)
child.addEventListener('click',doSomething,false)

如果它的最后一个参数为真,则事件处理程序设置为捕获阶段,如果为假,则事件处理程序设置为冒泡阶段。

引用示例代码并引用 this page :

If the user clicks on the child element the following happens:

  1. The click event starts in the capturing phase. The event looks if any ancestor element of child has a onclick event handler for the capturing phase.

  2. The event finds one on parent. doSomething2() is executed.

  3. The event travels down to the target itself, no more event handlers for the capturing phase are found. The event moves to its bubbling phase and executes doSomething(), which is registered to child for the bubbling phase.

  4. The event travels upwards again and checks if any ancestor element of the target has an event handler for the bubbling phase. This is not the case, so nothing happens.

我上面链接的页面有更多信息,但希望这能回答基本问题。

关于javascript - javascript中事件监听器的顺序是如何确定的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38508225/

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