Home  >  Article  >  Web Front-end  >  Jquery stops event bubbling event.stopPropagation_jquery

Jquery stops event bubbling event.stopPropagation_jquery

WBOY
WBOYOriginal
2016-05-16 17:58:321047browse

Description: Prevent events from bubbling up the DOM tree, that is, event handlers on any predecessor elements are not triggered.

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

This method is also valid for custom events triggered by trigger().

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

Additional Notes:
Since the .live() method handles the event once it propagates to the top of the document, it is impossible for the live event to stop propagating. Likewise, .delegate() events will always be propagated to the contained delegated element; events on the element will be executed when the delegated event is called.
Example:
Stop the bubbling of click events.

Copy code The code is as follows:

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


Things are not difficult, the main thing is to record the prevention event Bubble.

Because the div has added a click event, and the img inside the div has also added a click event, so when the img is clicked, the click event on the img will be triggered first, and then the click event on the div will be triggered. This is event bubbling.

We can easily stop him in Jquery.

As follows

Copy the code The code is as follows:
event.stopPropagation() ;

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

Copy code The code is as follows:

$('div').click(function(){
var $div = $(this);
if($div.find(' img').size() > 0){
return;
}else{
$div.css('backgroundColor','#e1f0f3');
$('').
appendTo($(this)).click(function(event){
$div .css('backgroundColor','#ffffff');
$(this).remove();
event.stopPropagation();
}).css('margin-left','10px ');
}
});
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