There are problems of event bubbles and event capture in javascript and jquery events. The following is a detailed summary of the two problems and their solutions.
Event bubbles are a process of bubbles from children to ancestor nodes;
Event capture is just the opposite, and is a process from ancestor nodes to children nodes.
Give an example of a jquery click event:
The code is as follows:
The code copy is as follows:
<!DOCTYPE html>
<meta charset="utf-8">
<title>test</title>
<head>
<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>
</head>
<body>
<div>
<button type="button" id="button2">click me</button>
<button id="clickMe">click</button>
</div>
</body>
</html>
Event bubble phenomenon: Click the button of "id=clickMe", and two pop-up boxes, "hello" and "baby" will appear one after another.
Analysis: When clicking on the button "id=clickMe", the click event bound to the button and button parent elements and body is triggered, so two boxes pop up one after another, and the so-called bubble phenomenon occurs.
Event capture phenomenon: If you click on the div and button that does not bind the click event, the "baby" dialog box will pop up.
In actual projects, we want to prevent event bubbles and event capture.
How to prevent events from bubbled:
Method 1: Return false in the current click event;
The code copy is as follows:
$('#clickMe').click(function(){
alert('hello');
return false;
});
Method 2:
The code copy is as follows:
$('#clickMe').click(function(event){
alert('hello');
var e = window.event || event;
if (e.stopPropagation ){ //If an event object is provided, then this is a non-IE browser
e.stopPropagation();
}else{
//IE-compatible way to cancel event bubble
window.event.cancelBubble = true;
}
});
It seems that the capture event cannot be blocked