Nested DIV elements, if the parent and child elements are bound to a number of events, then click on the most inner child elements may trigger the parent element of the event, the following describes the JS block default events and JS block event Bubbling example, please refer to the use of it
1. Event.preventdefault (); --Block The default event for an element.
Note: The click of a element to jump to the default event,
Default events for form elements such as Button,radio,
div element has no default event
Cases:
Copy CodeThe code is as follows:
<a href= "http://www.baidu.com" target= "_black" > Baidu </a>
Copy CodeThe code is as follows:
var samp = Document.getelementbytagname ("a");
Samp.addeventlistener ("click", Function (e) {e.preventdefault ()},false);
Explanation: Click the link when the normal situation will happen to jump, but now we have blocked its default event, that is, jump event, then will not jump to Baidu.
2. Event.stoppropagation (); --block element bubbling events
Note: Nested elements typically have bubbling events that can have some impact
Cases:
Copy CodeThe code is as follows:
<div id= "C1" onclick= "alert (1)" >
<div id= "C2" onlick= "alert (2)" >
<input type= "button" Id= "C3" Value= "click" onclick= "alert (3)" >
</div>
</div>
Click on the button here, the browser will pop up 3,2,1, originally just want to bind to the button on the event, but inadvertently triggered its two parents on the event, here we just did a simple test, imagine if in the project development, A button and his parent bind a very important event at the same time, and the result will be miserable. The way to do this is to stop the bubbling event.
Registers the Click event with input and blocks its bubbling event
Copy CodeThe code is as follows:
document.getElementById (' C3 '). AddEventListener (' click ', Function (e) {e.stoppropagation ()},false);
Ok!!! The
JS Block Browser, element default event and JS block event bubbling, block event flow