Jquery prevents event bubbling event. stopPropagation

Source: Internet
Author: User

Description: prevents events from bubbling to the DOM tree, that is, the event handler function on any previous element that is not triggered.

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

This method is also effective for events that are customized by trigger.

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

Additional Notes:
Since the. live () method handles events once they are propagated to the top of the document, live events cannot stop spreading. Similarly, the. delegate () event will always be transmitted to the delegate element contained in the event. The event on the element will be executed when the delegate event is called.
Example:
Kill click Event bubbles.Copy codeThe Code is as follows: $ ("p"). click (function (event ){
Event. stopPropagation ();
// Do something
});

It is not difficult, but it mainly records the blocking event bubbles.

Because a click event is added to the div, And the img inside the div also adds a click event, when you click img, The Click Event on the img is triggered first, and then the click event on the div is triggered, this is event bubbling.

In Jquery, we can easily block it.

As follows:

Copy codeThe Code is as follows: event. stopPropagation ();

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

Copy codeThe 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', '# ffff ');
$ (This). remove ();
Event. stopPropagation ();
}).Css ('margin-left', '10px ');
}
});

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.