test
< ;/html>
In the above HTML, the red element is the parent element of the green element.
$(function(){
$(" #green").click(function(event){
alert("green click1");
});
$("#green").click(function(event){
alert("green click2");
});
$("#red").click(function(event){
alert("red click");
});
});
The above js code adds three click events to the red element and green element.
When the sub-element green element is clicked, green click1, green click2, and red click events will be executed in sequence.
Event addition: Clicking on the green element will execute two events, green click1 and green click2 (events of the same type on the same element) in sequence.
Event bubbling: Clicking on the green element will trigger the red click event of the parent element (the same type of event of the parent element).
1. Prevent event bubbling in the child element event function
Method 1: event.stopPropagation()
$(function(){
$("#green").click(function(event){
event.stopPropagation();
alert("green click");
});
$("#red").click(function(event){
alert("red click");
});
});
Method 2: return false
$(function(){
$("#green").click(function(event){
alert("green click");
return false;
});
$("#red").click(function(event){
alert("red click");
});
});
Through the above two methods, after clicking the green area of the sub-element, the red click event is blocked and no longer executed. But it will not affect clicks in other areas of the red element.
The difference between the two:
return false is equivalent to event.preventDefault() event.stopPropagation().
2. Prevent event bubbling in the parent element event function
$(function(){
$("#green").click(function(event){
alert("green click");
});
$(" #red").click(function(event){
if(event.target == this)
{
alert("red click");
}
});
});
Use if(event.target== this) to determine whether the clicked target element is the red element itself. If it is not red itself but its sub-element green element, then no The code inside the if will be executed.
3. Prevent event appending
The above method can only prevent event bubbling (that is, events of the same type on the parent element), but cannot prevent event appending (events of the same type on the same element).
$(function(){
$(" #green").click(function(event){
event.stopImmediatePropagation();
alert("green click");
});
$("#green").click (function(){
alert("green click2");
});
});
event.stopImmediatePropagation() can not only prevent the green click2 event, but also Also prevents events from bubbling up.