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:
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn