Today I have a problem with this code as follows
var someth = document.getElementsByTagName ("a"); for (var i = 0; i < i++) { someth[i].addeventlistener ("click", Function () {alert (i)}) }
Found the problem, every time alert out of the same value 10 found on the Internet to find the original result of the closure of the packet.
I'll just stick to two solutions here.
Method One: Give Someth[i a property at the time of the loop, so that the value of alert out of I will change.
var someth= document.getelementsbytagname ("a"); for (var i = 0; I <10; i++) { someth[i].num = i; Someth[i].onclick = function () { alert (this.num); } }
Method Two: A function is nested outside the function.
var someth = document.getElementsByTagName ("a"); for (var i = 0; i <; i++) { someth[i].addeventlistener ("click", (function (num) { return function () { alert ("I am link" + num); } }) (i), "false"); }
PS: Attach the information I read http://segmentfault.com/q/1010000000626710
AddEventListener problems with loop binding