如何确定javascript中事件监听器的顺序? [英] How is the order of event listeners in javascript determined?

查看:97
本文介绍了如何确定javascript中事件监听器的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个包含链接(href)的div,并且有三个事件侦听器-单击-1)整个页面,2)div 3)一个标签.如果用户单击一个标签,如何触发侦听器?他们注册的顺序是什么?

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?

推荐答案

本质上,这要视情况而定.事件分为两个阶段:捕获(首先发生),将记录关闭,而冒泡将元素增加.

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)

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

如果最后一个参数为true,则为捕获阶段设置事件处理程序,如果为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:

  1. click事件在捕获阶段开始.该事件将查看child的任何祖先元素是否具有用于捕获阶段的onclick事件处理程序.

  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.

该事件在父项上找到一个. 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中事件监听器的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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