JS Loop Add Event

Source: Internet
Author: User

Usually we add events to elements like this:

var ul=document.getelementsbytagname ("ul") [0var list=document.getelementsbytagname (" Li ");
for (var i=0;i<li.length;i++) { List[i].onclick=function() { alert (" My index is "+i"; } }

But the result is often not as we imagined, they all pop up is "My index is 2", because JavaScript is a single-threaded execution of tasks, add events will be listed in the task order, so I value is all 2;

Workaround:

mode 1. Use closures. varUL = document.getElementsByTagName ("ul") [0]; varList = Ul.getelementsbytagname ("li");
functionfoo () { for(vari = 0, len = list.length; i < Len; i++){ varthat =List[i]; List[i].onclick= (function(k) {return function(){ Alert ("My index is" +k);
}; }) (i); }} foo ();
Mode 2. Event ProxyvarUL = Document.queryselector (' ul ')); varList = Document.queryselectorall (' ul Li '); Ul.addeventlistener (' Click ',function(){      varE = Arguments[0] | |window.event; vartarget = E.target | |e.srcelement;  for(vari = 0, len = list.length; i < Len; i++){          if(List[i] = =target) {              Alert ("My index is" +i);
} } });
mode 3. Introduce jquery, using the on or delegate event bindings (they all have the properties of the event broker)//Delegate Method$ ("ul"). Delegate ("Li", "click",function(){      varIndex = $ ( This). index (); varInfo = $ ( This). html (); Alert (Index+ "----" +info);   }); //On method$ ("ul"). On ("Click", "Li",function(){      varIndex = $ ( This). index (); varInfo = $ ( This). html (); Alert (Index+ "----" +info); });
Mode 4. Using the new feature in ES6 Let's declare that variables declared with let will have a block-level scope, which can obviously be achieved, but it's important to note that adding a ' use strict '(using strict mode) will take effect.  var ul = document.getElementsByTagName ("ul") [0];   var list = ul.getelementsbytagname ("li");     function foo () {' Use strict '      for (Let i = 0, len = list.length; i < Len; i++) {          
   
    function
    () {              this
    
    . InnerHTML);  }}} Foo ();  
   

For reference only, if there are errors please correct me!

JS Loop Add Event

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.