JavaScript, jquery events, event bubbling and event capture issues, the following two issues and their solutions to do a detailed summary.
Event bubbling is a process of bubbling from a child node to an ancestor node;
Event capture is just the opposite of the process from ancestor nodes to child nodes.
Give an example of a jquery click event:
The code is as follows:
<! DOCTYPE html>
<meta charset= "Utf-8" >
<title>test</title>
<script src= "Http://code.jquery.com/jquery-latest.js" ></script>
<script type= "Text/javascript" >
$ (function () {
$ (' #clickMe '). Click (function () {
Alert (' Hello ');
});
$ (' body '). Click (function () {
Alert (' Baby ');
});
});
</script>
<body>
<div style= "width:100px;height:100px;background-color:red;" >
<button type= "button" id= "Button2" >click me</button>
<button id= "ClickMe" >click</button>
</div>
</body>
Event bubbling phenomenon: click on "Id=clickme" button, will appear "Hello" and "Baby" two pop-up boxes.
Analysis: When clicked "Id=clickme" button, triggered the binding in the button and button and the parent element and body of the Click event, so has popped up two boxes, the so-called bubble phenomenon.
Event capture: Clicking the div and "id=button2" button without binding the event will pop up the "Baby" dialog box.
In the actual project, we want to prevent event bubbling and event capture phenomena.
To block event bubbling methods:
Method 1: The current click event return false;
$ (' #clickMe '). Click (function () {
Alert (' Hello ');
return false;
});
Law 2:
$ (' #clickMe '). Click (Function (event) {
Alert (' Hello ');
var e = window.event | | Event
if (e.stoppropagation) {//If an event object is provided, this is a non-IE browser
E.stoppropagation ();
}else{
Compatible with IE to cancel event bubbling
Window.event.cancelBubble = true;
}
});