JS bubble events
A few days ago, the boss came into contact with a new JS word: Bubble event;
What is a bubble event.
When multiple Div Nesting is set, that is, the parent-child relationship is established. When the parent Div and the Child Div join The onclick event together, when The onclick event of the Child div is triggered, subdiv to perform corresponding JS operations. However, The onclick event of the parent div is also triggered. This results in multi-layer concurrency of events and page confusion. This is a bubble event.
Elimination of bubble events
Prevents JavaScript event bubbling transfer (cancelbubble, stoppropagation)
The following sectionCodeThat is to say, it is a bubble effect and a bubble elimination effect.
<HTML>
<Head>
<Title> prevent javascript event 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; // determines the browser type. cancelbubble is used in IE-based browsers.
If (window. Event ){
E. cancelbubble = true;
} Else {
// E. preventdefault (); // supports stoppropagation in Firefox-based browsers.
E. stoppropagation ();
}
}
</SCRIPT>
</Head>
<Body>
<Div id = "parent1" onclick = "alert (this. ID)" style = "width: 250px; Background-color: yellow">
<P> This is parent1 Div. </P>
<Div id = "Child1" onclick = "alert (this. ID)" style = "width: 200px; Background-color: Orange">
<P> This is child1. </P>
</Div>
<P> This is parent1 Div. </P>
</Div>
<Br/>
<Div id = "parent2" onclick = "alert (this. ID)" style = "width: 250px; Background-color: cyan;">
<P> This is parent2 Div. </P>
<Div id = "child2" onclick = "dosomething (this, event);" style = "width: 200px; Background-color: lightblue;">
<P> This is child2. will bubble. </P>
</Div>
<P> This is parent2 Div. </P>
</Div>
</Body>
</Html>
Copy the Code directly. When you click Child1, the Child1 dialog box and parent1 are displayed.
This is a bubble event.
However, if you click chile2, only child2 is displayed, but parent2 is not displayed. This applies the effect of blocking the bubble event.