Refer to a question in an interview with a major factory, here is a review
Q: What is the event flow in JavaScript? How to deliver.
A: Let's split the problem first to see what is an event, what is an event flow, and finally how the event flow is delivered.
- Events are the way users implement page interactions.
- The event flow describes the order in which events are received from the page. In the early days, IE and Netscape put forward the completely opposite concept of event stream. IE event stream is event bubbling, while Netscape's event stream is event capture.
- When we by
addEventListener
the addition of DOM element event, do not pass the parameters, bubbling event:
This figure shows the flow of events in the downward direction code structure (event bubbling)
HTML
JavaScript
so as to print the above process sequence:
Q: There is a span element inside a div, and click events are added to both elements. How to make the event of the div start before the span and implement it using native JavaScript.
A: This problem is very simple, is to see the underlying API
enough familiar, we specify native JavaScript
add an event can use addEventListener
this API
, let's look MDN
on the face of this API
grammatical interpretation.
target.addEventListener(type, listener, options);
target.addEventListener(type, listener, useCapture);
target.addEventListener(type, listener, useCapture, wantsUntrusted ); // Gecko/Mozilla only
We can see that in addition to the first two parameters, there is a third parameter:
useCapture
: In the DOM tree, the element registered for the event should call the event before the EventTarget below it. When useCapture(set to true), events that bubble up the DOM tree will not trigger events. When one element is nested with another element, and both elements register a handler for the same event, event bubbling and event capture are two different event propagation methods. The event propagation mode determines the order in which elements receive events.
So we will be above JavaScript
modified as follows, you can allow registered event stream to capture the event:
order the registration event for print:
so in fact the realization of this issue is very simple, just to Parent
the event useCapture
set true
can be resolved.