JS event bubbling organizes the browser's event stream

Source: Internet
Author: User

  The interaction between JavaScript and HTML is implemented through events. The browser's event flow is a very important concept. Not to discuss those ancient browsers that have event capture and event bubbling controversy,

Just know that the event flow specified in DOM2 includes three parts, the event capture phase, the target stage, and the event bubbling phase.

1. Event capture

  Event capture, which starts with the document element, the more advanced the parent element receives the event earlier, so this is a top-down procedure.

A): Pit One: The newly inserted child element is not tied to a fixed-point-click event

A UL element in the initial state has 4 Li elements, we can loop to the LI element to add the click event, to perform the action we want. The pit of this example is that the newly added Li element does not have a click event that we bind.

  

  We can use event capture to deal with this problem

  

In the solution above, I did not directly bind the event to Li, but to all Li's parent UL binding events. Based on the principle of event capture, events are passed from top to bottom to Li, and we only need to determine our target elements by some simple conditional judgments, as in the example above to Judge Li's classname.

2. What if the target element has child elements

This is the case when we use ClassName to determine the target element.

    

  When we try to use the event delegate want to add elements to all Li, in the process of using classname to find that the target event.target element is actually Li.item child element, this time there is no way to accurately bind the event to Li, this time we should do? At this point we are going to stop the capture of events from passing. So how to stop it?

One way to know is to use CSS to add CSS properties to all of Li's child elements

   

JS event bubbling organizes the browser's event stream

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.