A netizen asked a question, such as the next HTML, why each output is 5, instead of clicking each p, alert out the corresponding 1,2,3,4,5.
There are several ways to solve this problem
1. Save the variable i on each paragraph object (p)
function init () {
var pary = document.getElementsByTagName ("P");
for (var i=0; i<pary.length; i++) {
pary[i].i = i;
Pary[i].onclick = function () {
alert (this.i);
}
}
}
2. Save the variable i to the anonymous function itself
function Init2 () {
var pary = document.getElementsByTagName ("P");
for (var i=0; i<pary.length; i++) {
(Pary[i].onclick = function () {
alert (ARGUMENTS.CALLEE.I);
}). i = i;
}
3. Add a layer closure, I pass the function parameter form to the inner layer function
function Init3 () {
var pary = document.getElementsByTagName ("P");
for (var i=0; i<pary.length; i++) {
(function (ARG) {
Pary[i].onclick = function () {
alert (arg);
};
}) (i);//Call time parameter
}
}
4. Add a layer closure, I pass to the memory function as local variable
function Init4 () {
var pary = document.getElementsByTagName ("P");
for (var i=0; i<pary.length; i++) {
(function () {
var temp = i;//called local variable
pary[i].onclick = function () {
alert (temp);
}
) ();
}
}
5, add a layer closure, return a function as a response event (note the subtle difference with 3)
function Init5 () {
var pary = document.getElementsByTagName ("P");
For (Var i=0. i<pary.length; i++) {
Pary[i].onclick = function (arg) {
return function () {//Returns a function
Aler T (ARG);
}
} (i);
}
6, with function implementation, in fact, each generated a function instance will produce a closure
function Init6 () {
var pary = document.getElementsByTagName ("P");
for (var i=0 i<pary.length; i++) {
Pary[i].onclick = new Function ("alert (+ i +);"); /new one function instance at a time
}
7, with function implementation, pay attention to the difference with 6
function Init7 () {
var pary = document.getElementsByTagName ("P");
for (var i=0; i<pary.length; i++) {
Pary[i].onclick = Function (' Alert (' +i+ ')
}
}}
The above is a small series for everyone to talk about JavaScript for the loop closure of the entire content, I hope that we support cloud-Habitat Community ~