As a career change just to the new company, the task is not many, this week to eliminate all tasks, leisure Day also do not idle, quietly read the book. Today write a JS event bubbling, capturing.
Also today to see a bit more content, some can not digest, it is handy to record a bit. Purely self-understanding, if there is not, please also guide the proposed, younger brother must correct.
Well, don't talk much. So what is event bubbling ?
For example, ul > li > Div > P. This time you click on p, and he will layer up and down until the last bound element of the event. If we bind the event on the UL, then click P, he will step up, until found the binding event of the UL will also trigger the event, then there is no element on it, he stopped.
If you do not understand, then there is no way, because of love, and then explain to you again. PS: Your family now has 4 people. Dad > Mom > you. All right, now your dad's in power. (Event bound in Granny's), when your grandfather took a nap, you were too ugly to wake him up, a slap in your face. You are happy to cry, go home to complain. The order you complain about this time is you > Mom > Dad. So you go back and see if the order is the same as the event bubble?
You don't know that, I'm going to have to code.
<! DOCTYPE html>"Utf-8"> <link rel="stylesheet"Type="Text/css"href="">"Text/css">#click {width:500px; height:500px; Background-color:red; Margin:0Auto; } #click2 {width:250px; height:250px; Background-Color:yellow; }</style><body><div id="Click"> <div id="Click2" class="son"></div></div><script type="Text/javascript">document.getElementById ("Click2"). AddEventListener ("Click", Function (e) {alert ("hit my dad, don't hit me,"); },false);
document.getElementById ("click"). AddEventListener ("click", Function (e) { alert ("Something hit me, don't hit my Son"); } , false);
</script> </body>
1. What happens if I click Id=click2, which is the second one? He will trigger the Click2 event first, then go up, then trigger the Click event.
2. When clicking on the Id=click element, it only triggers its own click event, as he bubbles up without the DOM element setting the Click event function.
So what is event capture ?
Just now, the event bubbling is going from the bottom to the bottom. So the catch is just the reverse, and it's going from the top floor to the inside.
That means just the ul > li > Div > P Example. Event bubbling is from P to UL, then event capture is UL to P. For example, by adding a click event Trigger, he starts from the root element and looks down at the child element that matches the event until he is found.
If you do not understand the two pictures, one is the event bubbling, one is the event capture. Self-reference (pictured by my soul painter's system, the shortcomings of the point of guidance)
Figure for event bubbling
The graph is event capture.
JS event bubbling, capturing. Learning record