<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
li{
list-style: none;
cursor: pointer;
}
</style>
<script type="text/javascript">
window.onload = function(){
var Ul = document.getElementById("ul");
var Li = Ul.getElementsByTagName("li");
Ul.onclick = function(ev){
var ev = ev || window.event;
var target = ev.target || ev.srcElement;
if(target.nodeName.toLowerCase() == "li"){
var index = 0;
for(var i=0;i<Li.length;i++){
if(Li[i]===target){
index=i;
};
}
if(index>=0){
alert('索引是'+index);
}
}
}
}
</script>
</head>
<body>
<ul id="ul">
<li>首页</li>
<li>新闻</li>
<li>娱乐</li>
</ul>
</body>
</html>
I would like to ask, is there a simpler way to obtain the index using event delegation?
Convert
children
toArray
and then callindexOf
directly. (Without considering compatibility...)Here is an example