How is the order of event listeners in javascript determined?

六月ゝ 毕业季﹏ 提交于 2019-12-11 00:58:00

问题


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?


回答1:


Essentially, it depends. There are 2 phases for events, Capturing (happens first), which goes document down, and Bubbling which goes element up.

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.

Referring back to the sample code and to quote 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.

The page I linked above has way more information, but hopefully that answers the basic question.



来源:https://stackoverflow.com/questions/38508225/how-is-the-order-of-event-listeners-in-javascript-determined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!