Discussion on what is event bubbling and how to cancel event bubbling!

Source: Internet
Author: User

In the process of learning jquery, we will certainly encounter the problem, that is event bubbling, then, what is the event bubbling?

Event bubbling the popular point is that when you register the same event with the parent element, when you activate the child element, the parent element is then activated .

Obviously, this is not the result we need! So we're going to try to cancel the event bubbling .

Specific examples are as follows

<body>    <div id="mybigdiv"> I am the         Big        div<div id="  myID"> I am a little div</div>    </div></body>

Here in my big div nested a small div, that is, the big Div has a subset of small Div

In the jquery code

$ (function () {$ ("#myid"). Click (function () {alert ('I am the child element of the Click event'); //Block Event bubbling//stop ();            }); $("#mybigdiv"). Click (function () {alert ('I am the parent element of the Click event');                    }); });

I also registered a click event for both the big Div and the small Div, and the code that blocks the event bubbling is commented out, so what happens when I click the small div?

The result is a click event that pops up I'm a child element and then pops up I'm a click event for the parent element so the result is something we don't want to see because it causes the event to bubble

So my solution here is to declare a function that blocks event bubbling stop () specific content is as follows

 //ways to resolve event bubblingfunction Stop () {//determine if the browser engine is IE or another browser            Event=Event|| Window.Event; if(Event. Stoppropagation) {                //non-IE browser                Event. Stoppropagation (); } Else {                //IE Browser                Event. cancelbubble =true; }        }

Then call this function in the child element's Click event to resolve the event bubbling problem!

Discussion on what is event bubbling and how to cancel event bubbling!

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.