SoFunction
Updated on 2025-03-04

Jquery prevents events from bubbled

Description: Prevent events from bubbled onto the DOM tree, that is, event handling functions on any predecessor elements that do not trigger.

version added: 1.0
()
We can use () to determine whether this method has been called (on that event object).

This method is also effective for trigger() custom events.

Note that this does not prevent other event handlers from running on the same element.

Additional Notes:
Since the .live() method handles events once they are propagated to the top of the document, it is impossible for the live events to stop propagating. Similarly, the .delegate() event will always be propagated to the delegated element contained in it; events on the element will be executed when the delegated event is called.
Example:
Destroy the bubbling of the click event.
Copy the codeThe code is as follows:

$("p").click(function(event){
();
// do something
});


Things are not difficult, mainly to record the blocking events that prevent them from bubbling.

Because the div adds a click event, and the img inside the div also adds a click event, so when clicking img, the click event on the img will be triggered first, and then the click event on the div will be triggered. This is the event bubble.

In Jquery we can easily stop him.

as follows

Copy the codeThe code is as follows:
();

In this way, clicking img will no longer trigger the div click event

Copy the codeThe code is as follows:

$('div').click(function(){
var $div = $(this);
if($('img').size() > 0){
return;
}else{
$('backgroundColor','#e1f0f3');
$('<img src="https:///lovejjhao/341157/o_cha.jpg"/>').
appendTo($(this)).click(function(event){
$('backgroundColor','#ffffff');
$(this).remove();
();
}).css('margin-left','10px');
}
});