There are many methods for binding Javascript events, which are flexible. However, as a relatively simple dynamic binding, the following code seems correct, but cannot achieve the expected results. Below is the dom structure of the page
The Code is as follows:
Below is the javascript code
The Code is as follows:
// Obtain the 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 [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:
The Code is as follows:
// Obtain the 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 (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.