Event bubbling/capturing - where does it start/end?

自作多情 提交于 2019-12-22 05:39:10

问题


I understand that an event has two modes -- bubbling and capturing.

When an event is set to bubble, does Javascript checks up to "document" ?

When an event is set to capture, does Javascript always starts from "document"?

How does Javascript know where to stop/start ?

Update:

Let's say I have the following code in my body tag.

<div id='outer'>
    <div id='inner'></div>
</div>

When I set an event to #inner to bubble, does Javascript check up to document or does it stop at #outer?


回答1:


Event bubbling

JavaScript checks all the way up to document. If you add a listener on document and a listener on inner, both listeners fire.

Event capturing

JavaScript starts from document and goes all the way down to inner. If you add a listener on document and a listener on inner, both listeners fire.


My Findings

Turns out that the browser does some sort of smart processing so that it

a) doesn't have to loop through the entire parent hierachy

and

b) doesn't have to loop through all events.


Proof

a) It takes the browser no time to trigger both click events when the inner div is clicked:

Fiddle

b) It takes the browser no time to trigger both click events when the inner div is clicked when lots of other events exist that are attached to other DOM elements not in the parent hierachy:

Fiddle




回答2:


From W3C Document Object Model Events

I know I'm nitpicking but it isn't javascript that handles the events you are describing, it is the DOM-engine (Document Object Model). In the browser there are bindings between the javascript and DOM engines so that events can be propagated to javascript, but it is not limited to javascript. For example MSIE has support for BASIC.

When an event is set to bubble, does Javascript checks up to "document" ?

1.2.3 "This upward propagation will continue up to and including the Document"

"Any event handler may choose to prevent further event propagation by calling the stopPropagation method of the Event interface. If any EventListener calls this method, all additional EventListeners on the current EventTarget will be triggered but bubbling will cease at that level"

When an event is set to capture, does Javascript always starts from "document"?

1.2.2 "Capture operates from the top of the tree, generally the Document,"




回答3:


Partial answer..

1 - When an event is set to bubble, does Javascript check up to "document" ?

Not if one of the elements in the hierarchy decides to stop the bubbling by calling stopPropagation()



来源:https://stackoverflow.com/questions/12576116/event-bubbling-capturing-where-does-it-start-end

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