Today, when I was learning JavaScript, I encountered a problem similar to the following code:
/** * <body> * <ul> * <li>one</li> * <li>two</li> * <li>three</li> * <li>one</li> * </ul> */var lists = document.getElementsByTagName(‘li‘);for(var i = 0 , len = lists.length ; i < len ; i++){ lists[ i ].onmouseover = function(){ alert(i); };}
During function execution, we will find that the value displayed in the pop-up window is always 4 (that is, the final value of the loop variable I in the parent function), instead of the expected values 0, 1, 2, 3. the reason is: when the Mouseover event calls the listener function, first check whether I is defined in the anonymous function () {alert (I) ;}). The result is not defined; therefore, it will search up, the search result is defined, and the I value is 4 (The I value after the loop); therefore, each pop-up is 4.
Possible solutions: [1]:
//method 1
var lists = document.getElementsByTagName(‘li‘);for(var i = 0 , len = lists.length ; i < len ; i++){ (function(index){ lists[ index ].onmouseover = function(){ alert(index); }; })(i);}
// Method 2var lists = document. getelementsbytagname ('lil'); For (VAR I = 0, Len = lists. length; I <Len; I ++) {lists [I]. $ Index = I; // record the subscript lists [I] by binding $ index to the DOM element. onmouseover = function () {alert (this. $ index );};}
//method 3function eventListener(list, index){ list.onmouseover = function(){ alert(index); };}var lists = document.getElementsByTagName(‘li‘);for(var i = 0 , len = lists.length ; i < len ; i++){ eventListener(lists[ i ] , i);}
In the preceding method, method 1 is available and recommended.
Reference
[1]Anonymous functions and function closures in JavascriptHttp://www.cnblogs.com/rainman/archive/2009/05/04/1448899.html
The closure allows the inner function to reference a variable in the parent function, but the variable is the final value.