There are problems with event bubbling and event capture in JavaScript and jquery events. The two problems and their solutions are summarized in detail below.
Event bubbling is a process of bubbling from child nodes to ancestor nodes;
Event capture is just the opposite, a process from ancestor nodes to child nodes.
Give an example of jquery click event:
The code is as follows:
Event bubbling phenomenon: Click the button with "id=clickMe", and two pop-up boxes "hello" and "baby" will appear successively.
Analysis: When the button with "id=clickMe" is clicked, the click event bound to the button, button parent element and body is triggered, so two boxes pop up one after another, causing the so-called bubbling phenomenon.
Event capture phenomenon: When you click on a div that has no click event bound and a button with "id=button2", the "baby" dialog box will pop up.
In actual projects, we need to prevent event bubbling and event capturing.
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 the event object is provided, this is a non-IE browser
e.stopPropagation();
}else{
//An IE-compatible way Cancel event bubbling
window.event.cancelBubble = true;
}
});
It seems that capturing events cannot be blocked