<!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>
我想问一下,这种用事件委托的方式获取索引的方式,有没有更加简单的方法呢?
children
转换为Array
,然后直接调用indexOf
。(没考虑兼容性……)这里有个例子