Home  >  Article  >  Web Front-end  >  Detailed summary of js bubbling, capturing events and preventing bubbling methods_javascript skills

Detailed summary of js bubbling, capturing events and preventing bubbling methods_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:49:261605browse

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:

Copy code Code As follows:



test









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;
Copy code The code is as follows:

$('#clickMe').click(function(){
alert('hello');

return false;
});

Method 2:
Copy code The code is as follows:

$('#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
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn