Two ways to block event bubbling with JS

Source: Internet
Author: User

I. Introduction to bubbling Events

When we click on a control, if the parent control that includes the control also has the Click event, it will continue to execute.

Method One: Event.stoppropagation ();

For example:

<div><p>Paragraph text content<input Type="Button" Value=Click /> </p></div>    

HTML code:

Bind the Click event for all DIV elements$("Div").Click( function(Event){Alert("Div-click");} );Bind the Click event for all P elements$("P").Click( function(Event){Alert("P-click");} );Bind the Click event for all button elements$(": Button").Click( function(Event){Alert("Button-click");Block events from bubbling to the DOM treeEvent.Stoppropagation(); //only executes the click of the button, and if the line is commented out, the click   }      

Method Two: Event.target

EventEvent.targetDOM APIJquery. TargetDomThisDom$ (document). Ready (function () {
$ (' #switcher '). Click (Function (event) {
$ (' #switcher. Button '). Toggleclass (' hidden ');
})
})

$ (document). Ready (function () {
$ (' #switcher '). Click (Function (event) {
if (event.target==this) {
$ (' #switcher. Button '). Toggleclass (' hidden ');
}
})
})
<div id= "switcher" > .

JS Block event bubbling in two ways

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.