Detailed summary of js bubbling capturing events and stopping bubbling methods

  • 2020-03-30 02:54:13
  • OfStack

The problems of event bubbling and event capture exist in the events of javascript and jquery. The two problems and their solutions are summarized in detail below.

Event bubbling is a bubbling process from child node to ancestor node.

Event capture is the opposite, from the ancestor node to the child node.

Give an example of a jquery click event:

The code 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 style="width:100px;height:100px;background-color:red;"> 
<button type="button" id="button2">click me</button> 
<button id="clickMe">click</button> 
</div> 
</body> 
</html> 

Event bubble phenomenon: click "id=clickMe" button, will appear "hello" and "baby" two pop-ups.

Analysis: when the button with "id=clickMe" is clicked, the click events bound to the button, the parent element of the button and the body of the button are triggered. Therefore, two boxes pop up successively and the so-called bubble phenomenon appears.


Event capture phenomenon: clicking on a div without a binding click event and on a button with "id=button2" will bring up the "baby" dialog.


In a real project, we would prevent event bubbling and event capture.

Methods to prevent event bubbling:

Method 1: return false in the current click event;
 
$('#clickMe').click(function(){ 
alert('hello'); 

return false; 
}); 

Method 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 IE way to cancel event bubbling
window.event.cancelBubble = true; 
} 
}); 

It seems that capture events cannot be stopped

Related articles: