How is the order of event listeners in javascript determined?(javascript中事件监听器的顺序是如何确定的?)
问题描述
假设有一个 div 包含一个链接 (a href) 并且有三个事件侦听器 - on-click- 1) 用于整个页面,2) 在 div 上 3) 一个标签.如果用户点击 a 标签,监听器是如何被触发的?它们的注册顺序是什么?
Suppose there is a div which contains a link ( a href) and there are three event listeners - on-click- 1) for the entire page, 2) on div 3) a tag. If the user clicks on the a tag, how are the listeners triggered? What is the order of them being registered?
推荐答案
基本上,这取决于.事件有 2 个阶段,捕获(首先发生),文档向下,冒泡,元素向上.
Essentially, it depends. There are 2 phases for events, Capturing (happens first), which goes document down, and Bubbling which goes element up.
JS 两者都可以,这就是为什么在创建自定义事件监听时你有第三个布尔变量,例如
JS can do both, which is why when creating a custom Event listened you have the third boolean variable, e.g.
parent.addEventListener('click',doSomething2,true)child.addEventListener('click',doSomething,false)
如果它的最后一个参数为真,则为捕获阶段设置事件处理程序,如果为假,则为冒泡阶段设置事件处理程序.
If its last argument is true the event handler is set for the capturing phase, if it is false the event handler is set for the bubbling phase.
参考示例代码并引用本页:
如果用户点击子元素会发生以下情况:
If the user clicks on the child element the following happens:
点击事件在捕获阶段开始.该事件查看 child 的任何祖先元素是否具有捕获阶段的 onclick 事件处理程序.
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.
事件在父节点上找到一个.doSomething2() 被执行.
The event finds one on parent. doSomething2() is executed.
事件向下传播到目标本身,找不到更多的捕获阶段的事件处理程序.该事件进入其冒泡阶段并执行 doSomething(),该事件已注册到子冒泡阶段.
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.
事件再次向上传播并检查目标的任何祖先元素是否具有冒泡阶段的事件处理程序.事实并非如此,所以什么也没有发生.
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.
我上面链接的页面有更多信息,但希望能回答基本问题.
The page I linked above has way more information, but hopefully that answers the basic question.
这篇关于javascript中事件监听器的顺序是如何确定的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:javascript中事件监听器的顺序是如何确定的?
基础教程推荐
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01