What is bubbling:
Simply put is the event that triggers a child container, and the event of the parent container is then triggered.
<div id= "Parentdiv" onclick= "alert (' parent ');" > Parent <div id= "Childdiv" onclick= "alert (' child ');" >child</div></div>
The alert (' child ') and alert (' parent ') events are added to child and parent respectively, and if we click on Child, we will first execute alert (' child ') and then the parent element's alert (' Parent ') will also be executed, of course, if there are more levels, the parent event will be triggered sequentially, which is bubbling.
But sometimes I do not need such a mechanism, as we click on the child only to trigger the child on the alert (' child ') event, then we will stop bubbling.
How do I stop bubbling?
Blocking bubbles has the following methods:
E.cancelbubble=true;e.stoppropagation (); return false;
E.stoppropagation (); it's for Firefox, E.cancelbubble=true; it's for IE.
Here's an example:
<div id= "Parentdiv" onclick= "alert (' parent ');" > parent <div id= "Childdiv" onclick= "dosomething (this,event);" >child</div></div><script> function dosomething (obj,evt) { var e=evt| | window.event; E.stoppropagation (); }</script>
Because the bubbles are blocked in the dosomething, the alert (' Parent ') event on the Parentdiv is not triggered.
How to use bubbling?
Of course, sometimes we will use bubbles to meet our needs, for example, there are many elements to add an event to deal with something, but if the element is added to the onclick, first performance does not say, so many of the code will also make people scoff, which can be used to bubble.
Because the triggering of these element events can be bubbling to trigger the events of his father, just add the incident to his father, and then judge exactly what the element's time is triggered. Then you can do whatever you like.
Example:
<table onclick= "Clicktd", "width=", "height=", border= "1" > <tr> <td id= "TD1" width = "25%" >td1</td> <td id= "TD2" width= "25%" >td2</td> <td id= "td3" width= "25%" >td3< ;/td> <td id= "td4" width= "25%" >td4</td> </tr></table><script> function C LICKTD (e) { var e = e| | window.event; var obj = e.target| | E.srcelement; alert (obj.id); } </script>
Event.target represents the element in which the click event occurred;
Note: The event.target of a tag returns its href instead of the a tag itself, and if you want to return the DOM, you can take advantage of outerhtml;event.target.outerhtml
The main point here is to get the exact element by E.target or e.srcelement (depending on the browser). We should know what to do next.
About JavaScript bubbling (event delegation)