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