<!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>
<li>首页</li>
<li>新闻</li>
<li>娱乐</li>
</ul>
</body>
我想問一下,這種用事件委託的方式取得索引的方式,有沒有更簡單的方法呢? ###
習慣沉默2017-06-08 11:05:05
children
轉換為Array
,然後直接呼叫indexOf
。 (沒考慮相容性…)
<ul id="ul">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
const ul = document.querySelector('#ul')
const children = Array.prototype.slice.call(ul.children)
ul.onclick = (ev) => {
const target = ev.target;
console.log('current index', children.indexOf(target))
}
這裡有個例子