Dom's AddEventListener function is a trap.

Source: Internet
Author: User

This function is a DOM Level3-level method that registers events with the use of:

Dom object. AddEventListener ("event name (such as click)", the function that the event executes (which can be an anonymous function or a functional name), False/true (False indicates the Bubbling method, true means the Capture method));

Note here that the second parameter does not seem to compile immediately (of course, JS is not compiled, just to express), but only when the event is triggered to run the code inside, including variable assignment.

Like the code below.

<a href= "# #" > Connect a </a><a href= "# # #" > Connect two </a><a href= "# #" > Connection three </a><a href= "# # # "> Connection four </a><a href=" # # # "> Connection five </a><a href=" # # "> Connection six </a><a href=" # # "> Connection seven </a ><a href= "# #" > Connection eight </a><a href= "# #" > Connection nine </a><script>var myhref = document.getElementsByTagName ("a");  for (var i = 0,mylength = myhref.length; i<mylength; i++) {    Myhref[i].addeventlistener ("click", function (e) {        e.preventdefault ();        alert (i);    },"false"); </script>

We hope that the result of clicking on each a will pop up the corresponding array label value, that is, the first a click after the display 0, the second display 1. But in fact we find that this is not the result, but instead always shows the array designator value of the last a-label object +1, which is 9.

So I think that the function is not executed immediately, but only the reference to the function is placed there, when the event occurs, only to invoke the actual function body, and I as a global variable, has been preserved, if we finally done another operation on I, such as this:

<script>var myhref = document.getElementsByTagName ("a");  for (var i = 0,mylength = myhref.length; i<mylength; i++) {    Myhref[i].addeventlistener ("click", function (e) {        e.preventdefault ();        alert (i);    },"false"); I=555; </script>

Each connection pops up with 555. The actual i is done as a global variable (JS no block scope, so the for loop i is not a local variable, but a global variable), and I think, if I let the memory back, it will be an error, the result I tried not to recycle, probably because of the closure of the relationship. In fact, even if the browser is a global function is a closure, specifically why I understand here, we can find a closure of the relevant information to see.

So how to achieve the effect we want, or we have to use closures ah, we need to save the then I. The code is as follows:

<script>var myhref = document.getElementsByTagName ("a");  for (var i = 0,mylength = myhref.length; i<mylength; i++) {    (function(i) {  // I with the outside I is not actually an I        myhref[i].addeventlistener ("click",function(e) {            E.preventdefault ();            alert (i);        },"false");    }) (i);} I=555;    // does not affect </script>

In this case, it is actually an immediate function expression in the For loop, which is executed immediately, executes our closures immediately, we pass the I parameter to the closure, the I in the closure is only in the closure, and the external i is not an I, so we can achieve the desired effect.

The summary is not good, forgive me.

The AddEventListener function of the

Dom is a trap.

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.