Dachang interview review

Insert picture description here

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 addEventListenerthe 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)
    Insert picture description here
    HTML
    Insert picture description here
    JavaScript
    Insert picture description here
    so as to print the above process sequence:
    Insert picture description here

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 APIenough familiar, we specify native JavaScriptadd an event can use addEventListenerthis API, let's look MDNon the face of this APIgrammatical 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 JavaScriptmodified as follows, you can allow registered event stream to capture the event:
Insert picture description here
order the registration event for print:
Insert picture description here
Insert picture description here
so in fact the realization of this issue is very simple, just to Parentthe event useCaptureset truecan be resolved.

Guess you like

Origin blog.csdn.net/weixin_45958151/article/details/114948791