两种方法实现,第一种为事件委托,第二种为闭包。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <ul id="container"> <li class="li">1</li> <li class="li">2</li> <li class="li">3</li> <li class="li">4</li> <li class="li">5</li> </ul> </body> <script> var ul = document.querySelector('#container'); ul.addEventListener("click",function(event){ var event = event || window.event; var src = event.target || event.srcElement; for (var i = 0; i < this.children.length; i++) { if (src.nodeName.toLowerCase()=='li' && src == this.children[i]) { console.log(i); } } },false) var lis = document.querySelectorAll(".li"); for(var i = 0; i< lis.length; i++) { lis[i].onclick = (function(i) { return function(){ console.log(i); } })(i); } </script> </html>