The following is the DOM structure of the page
Copy Code code as follows:
<ul id= "Test" >
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>
Here is the JavaScript code
Copy Code code as follows:
Get an object from an ID
function ID (v) {return document.getElementById (v);}
Get objects from tags
function tag (element, T) {return element.getelementsbytagname (t);}
Window.onload = function () {
Get all of the Li objects under test
var li = tag (ID ("test"), "Li");
Loop-bound Mouse click event
for (var i=0; i<li.length; i++) {
Li[i].onclick = function () {
Expect pop-up 1,2,3,4
The result pops up always 5
Alert ("You clicked the first" + (i+1) + "item");
}
}
}
Why is there the image above? The reason is "the event bindings in for are not immediately executed." The modified code is as follows:
Copy Code code as follows:
Get an object from an ID
function ID (v) {return document.getElementById (v);}
Get objects from tags
function tag (element, T) {return element.getelementsbytagname (t);}
Window.onload = function () {
Get all of the Li objects under test
var li = tag (ID ("test"), "Li");
Loop-bound Mouse click event
for (var i=0; i<li.length; i++) {
(function () {
var t = i
Li[i].onclick = function () {
Alert ("You clicked the first" + t + "item");
}
})();
}
}
Test code, everything OK, we normally pass the loop variable i to the OnClick event corresponding to the handler function.