Below is the DOM structure of the page
CopyCode The Code is as follows: <ul id = "test">
<Li> one </LI>
<Li> two </LI>
<Li> three </LI>
<Li> four </LI>
</Ul>
Below is the JavaScript codeCopy codeThe Code is as follows: // obtain an object by ID
Function ID (v) {return document. getelementbyid (V );}
// Obtain Objects Based on tags
Function tag (element, T) {return element. getelementsbytagname (t );}
Window. onload = function (){
// Obtain all Li objects under test
VaR li = tag (ID ("test"), "Li ");
// Bind the mouse to the event cyclically
For (VAR I = 0; I <li. length; I ++ ){
Li [I]. onclick = function (){
// Expected pop-up: 1, 2, 3, 4
// The result is always 5
Alert ("the number you clicked" + (I + 1) + "item ");
}
}
}
Why is the above image displayed? The reason is that "event binding in for is not executed immediately ". The modified code is as follows:Copy codeThe Code is as follows: // obtain an object by ID
Function ID (v) {return document. getelementbyid (V );}
// Obtain Objects Based on tags
Function tag (element, T) {return element. getelementsbytagname (t );}
Window. onload = function (){
// Obtain all Li objects under test
VaR li = tag (ID ("test"), "Li ");
// Bind the mouse to the event cyclically
For (VAR I = 0; I <li. length; I ++ ){
(Function (){
VaR T = I
Li [I]. onclick = function (){
Alert ("You clicked item" + T + ");
}
})();
}
}
Test code. Everything is OK. we normally upload the Circular Variable I to the processing function corresponding to the onclick event.