Method one, use event bubbling to delegate to the parent node of the list for processing:
var ulObj = document.getElementById("myUl");
ulObj.onclick = function (event) {
var tg = event.target;
var liArray = ulObj.getElementsByTagName("li");
for (var i = 0; i < liArray.length; i ) {
if (liArray[i] === tg) {
alert(i 1);
}
}
}
Method 2, use closure :
var liArray = document.getElementById("myUl").getElementsByTagName("li");
for (var i = 0; i < liArray.length; i ) {
(function () {
var n = i;
liArray[i].onclick = function () {
alert(n 1);
}
})(i)
}
HTML code: