<! doctype html> },true) Father.addeventlistener ("Click", Function (e) {console.log (e.eventphase); Console.log (E.target); Console.log ("father");
},false) var Son=document.getelementbyid ("Son"); Son.addeventlistener ("click", Function (e) {console.log ("son"); Console.log (e.eventphase); }) </script> First put the code, you create an arbitrary HTML file, such as a.html, and then put this piece of code in.
Open with Chrome browser and review the elements, the final interface is as follows:
This gives two layers, one id=father, the outermost layer, and the other Id=son the innermost layer.
By the way, the browser's event delivery type is briefly described.
Microsoft and early Netscape used event bubbling and event capture, and then formed the current browser's event mechanism.
Event bubbling means that when I click Son, son receives this event message and passes it to father,
Event capture is the opposite, first father receives the event, then son.
Then ES (the standard JS,ECMA java script) specifies the sequence of events to be captured first, then to event processing, and then to the bubbling phase.
Does that mean I'm going to go through father and then go to son and then bubble to father after a click event?
We know that the DOM2 method for element snooping is Xx.addeventlistener ("event name", "handler function", "whether capture")
By default, the third parameter is false, which means that it is not captured and only bubbled.
Return to our code, you can see me here to father write two listener functions, one is capture, one is bubbling, then let's click the inner element to see what happens.
You can see the output of the two Father processing function output event object, which is son, sequentially.
I wrote in the Listening function Console.log (e.eventphase), this is the event processing phase
1-Capture 2-Handle 3 bubbling
So here is the output in order. Prove that the browser follows this principle, of course, we usually write event monitoring will not be for the same element of the event write two processing sequence different processing functions, usually write is based on bubbling.
So we take the second listening function off and look at it.
Found only 2, 3 output, again confirms this fact.
The mechanism of event bubbling allows us to write event delegates to replace the same n-element write listener functions that are intrinsic to an element. Event delegate Introduction I'll give it to you later.
Front End-"learning experience"-talk about event bubbling and event capture