What is a bubbling event?
That is, when multiple divs are nested; that is, a parent-child relationship is established. When the parent div and the child div join the onclick event, when the onclick event of the child div is triggered, the child div performs the corresponding js operation. But the onclick event of the parent div will also be triggered. This results in multiple levels of concurrency of events, leading to page chaos. This is a bubbling event.
How to eliminate bubbling events
Prevent JavaScript events from bubbling (cancelBubble, stopPropagation)
The following piece of code can explain very well what is the bubbling effect and what is the elimination of the bubbling effect?
Copy the code code as follows:
<html>
<head>
<title> Prevent JavaScript events from bubbling (cancelBubble, stopPropagation)</title>
<meta name="keywords" content="JavaScript, event bubbling, cancelBubble, stopPropagation" />
<script type="text/javascript">
function doSomething (obj,evt) {
alert(obj.id);
var e=(evt)?evt:window.event; //Determine the browser type and use cancelBubble in browsers based on the IE kernel
if (window.event) {
e.cancelBubble=true;
} else {
//e.preventDefault(); //Support the stopPropagation method in browsers based on the firefox kernel
e.stopPropagation();
}
}
</script>
</head>
<body>
<div id="parent1" onclick="alert(this.id)">
<p>This is parent1 div.</p>
<div id="child1" onclick="alert(this.id)">
<p>This is child1.</p>
</div>
<p>This is parent1 div.</p>
</div>
<br />
<div id="parent2" onclick="alert(this.id)">
<p>This is parent2 div.</p>
<div id="child2" onclick="doSomething(this,event);">
<p>This is child2. Will bubble.</p>
</div>
<p>This is parent2 div.</p>
</div>
</body>
</html>
After copying the code directly, when you click on child1, not only the child1 dialog box will pop up, but also the parent1 dialog box will pop up.
This is the bubbling event
But clicking chile2 will only pop up child2 but not parent2. This is the effect of applying special effects that prevent bubbling events.