Home  >  Article  >  Web Front-end  >  Two ways to implement click list pop-up list index_javascript skills

Two ways to implement click list pop-up list index_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:40:461255browse
Method one, use event bubbling to delegate to the parent node of the list for processing:
Copy code The code is as follows:

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 :
Copy code The code is as follows:

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:
Copy code The code is as follows:


  • haha

  • heihei

  • hehe

  • gaga
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