]
The above scenario is common for beginners Encountered. That is, get a collection of HTML elements and add events to the elements in a loop. Obtain the corresponding index in the event response function (event handler). But each time it gets the index of the last loop.
The reason is that beginners do not understand the closure feature of JavaScript. Add a click event to the element through element.onclick=function(){alert(i);}. The i in the response function function(){alert(i);} is not the i corresponding to each loop (such as 0, 1, 2, 3, 4) but the value 5 of the last i after the loop. In other words, the corresponding value i was not saved in the response function during the loop, but the value of i was 5 for the last time.
Understood the reason and found many solutions (just out of interest). The first two that come to mind
1. Save the variable i on each paragraph object (p)
The code is as follows:
function init1() {
var pAry = document.getElementsByTagName("p");
for( var i=0; i
pAry[i].i = i;
pAry[i].onclick = function() {
alert(this.i);
}
}
}
2. Save the variable i in the anonymous function itself
The code is as follows:
function init2() {
var pAry = document.getElementsByTagName("p");
for( var i=0; i
(pAry[i].onclick = function() {
alert(arguments.callee.i);
}).i = i;
}
}
Then I thought of three more
3. Add a layer of closure, and pass i to the inner function in the form of a function parameter
The code is as follows:
function init3() {
var pAry = document.getElementsByTagName("p");
for( var i=0; i
(function(arg){
pAry[i].onclick = function() {
alert(arg);
};
})(i); //Parameters when calling
}
}
4. Add a layer of closure, i is passed to the inner function in the form of a local variable
The code is as follows:
function init4() {
var pAry = document.getElementsByTagName("p");
for( var i=0; i
(function () {
var temp = i;//Local variable when calling
pAry[i].onclick = function () {
alert(temp);
}
})();
}
}
5. Add a layer of closure and return a Function as response event (note the subtle difference with 3)
The code is as follows:
function init5() {
var pAry = document.getElementsByTagName("p");
for( var i=0; i
pAry[i].onclick = function (arg) {
return function() {//Return a function
alert(arg);
}
}(i);
}
}
Later, two more types were discovered
6. Use Function to implement. In fact, every time a function instance is generated, a closure will be generated
The code is as follows:
function init6() {
var pAry = document.getElementsByTagName("p");
for( var i=0; i
pAry[i].onclick = new Function("alert(" i ");");//new generates a function instance once
}
}
7. Use Function to implement, pay attention to the difference with 6
The code is as follows:
function init7() {
var pAry = document.getElementsByTagName("p");
for( var i=0; i
pAry[i].onclick = Function('alert(' i ')');
}
}