A simple example to discuss the problem of JS capturing and bubbling

Source: Internet
Author: User

Event bubbling with event capture, here is an example of capturing and bubbling in JS:
HTML structure:

<divid="tianzi">    <divid="tianzi1">        <divid="tianzi2">            <divid="tianzi3">            </div>        </div>    </div></div>

CSS style control:

#tianzi{  width: px;     height: px;  background: red; }#tianzi1{  width: px;     height: px;  background: yellow; }#tianzi2{  width: px;     height: px;  background: Green; }#tianzi3{  width: + px;     Height: + px;  background: Blue; }

JS section:

Window.onload= function(){    varXtianzi=document.getelementbyid ("Tianzi");varXxtianzi=document.getelementbyid ("Tianzi1");varXxxtianzi=document.getelementbyid ("Tianzi2");varXxxxtianzi=document.getelementbyid ("Tianzi3");varf= function(){Alert"Message")} Document.addeventlistener ("click", function(){Alert"You clicked the document"); },false); Document.body.addEventListener ("click", function(){Alert"You clicked on the body"); },false); Xtianzi.addeventlistener ("click", function(){Alert"You clicked the Big box."); },false); Xxtianzi.addeventlistener ("click", function(){Alert"You clicked on the Little box."); },false); Xxxtianzi.addeventlistener ("click", function(){Alert"You clicked the 200 box."); },false); Xxxxtianzi.addeventlistener ("click"Ffalse); Xxxxtianzi.removeeventlistener ("click"Ffalse); }

Event bubbling and event capture are presented by Microsoft and Netscape, respectively, to address the issue of event flow (sequence of events) in the page.

<divid="outer">    id="inner"me!</p></div>

One of the DIV elements in the above code has a P child element, and if two elements have a click handler, how do we know which function will be triggered first?

To solve this problem, Microsoft and Netscape put forward two concepts that are almost completely opposite to each other.

Event bubbling

Microsoft has proposed an event stream called event bubbling. Event bubbling can be figuratively likened to putting a stone into the water, and bubbles will come up from the bottom. That is, the event starts from the most inner element and propagates upward until the document object.

So the above example takes place under the concept of event bubbling. The order of the click events should be HTML--

Event capture

Netscape proposes another event stream named event capturing. In contrast to event bubbling, events start from the outermost layer until the most specific element.

In the above example, the order in which the Click event takes place under the concept of event capture should be the page, HTML--

The third parameter of a AddEventListener

The event streams specified in the "DOM2 level event" support both the event capture phase and the event bubbling phase, and as a developer we can choose which phase the event handler is called.

The AddEventListener method is used to bind an event handler to a particular element, which is a common method in JavaScript. The AddEventListener has three parameters:

Element.addeventlistener (event, function, Usecapture)
The first parameter is the event that needs to be bound, and the second parameter is the function to execute after the event is triggered. The third parameter, the default value, is false, which means that the event handler is called during the event bubbling phase, and if the argument is true, the handler function is called during the event capture phase. Take a look at the example.

Event Proxy

In actual development, we can use a method called event broker, which uses the characteristics of the event stream.

<ul id="Color-list">    <li>Red</li>    <li>Yellow</li>    <li>Blue</li>    <li>Green</li>    <li>Black</li>    <li>White</li></ul>

If you click on the LI element in the page and then output the colors in Li, we will usually write this:

(function(){var color_list = document.getElementById(' color-list ');var colors = Color_list.getelementsbytagname(' li ');For(var i=0; i<colors.length;i++) {Colors[i].addeventlistener (' click ', sh    Owcolor,false);    };        function Showcolor(e){var x = E.target; Alert("The color is" + x.innerhtml); } ;})();

Using the nature of the event stream, we can only bind an event handler function to complete:

(function(){var color_list = document.getElementById(' color-list ');    Color_list.addeventlistener(' click ', Showcolor,false);        function Showcolor(e){var x = E.target; If(x.nodename.tolowercase() = = = ' li '){alert(' the color I S ' + x.innerhtml); }    }})();

The benefit of using event proxies is not only to reduce the number of event handlers to one, but also to have different ways of handling different elements. If other elements are added to the above list elements (such as: A, span, etc.), we do not have to cycle through each element to bind the event, directly modify the event handler function.

Bubble or catch?

For event proxies, there is no obvious advantage in event capture or event bubbling, but because event bubbling is compatible with all major browsers, the event bubbling model is recommended from a compatibility standpoint.

IE Browser compatible

IE browser to AddEventListener compatibility is not too good, only IE9 above can be used.

AddEventListener compatibility

To be compatible with older versions of IE, you can use IE's attachevent function

Object.attachevent (event, function)
The two parameters are similar to AddEventListener, which are event and handler functions, the default is the event bubbling stage call handler function, note that the write event name should be prefixed with "on" ("onload", "onclick", etc.).

A simple example to discuss the problem of JS capturing and 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.