javascript - JS事件委托問(wèn)題
問(wèn)題描述
<!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>首頁(yè)</li><li>新聞</li><li>娛樂(lè)</li>
</ul>
</body></html>
我想問(wèn)一下,這種用事件委托的方式獲取索引的方式,有沒(méi)有更加簡(jiǎn)單的方法呢?
問(wèn)題解答
回答1:children轉(zhuǎn)換為Array,然后直接調(diào)用indexOf。(沒(méi)考慮兼容性……)
<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))}
這里有個(gè)例子
相關(guān)文章:
1. bootstrp是col-md-12列的,只有col-md-10有內(nèi)容,可以讓沒(méi)有內(nèi)容的不占據(jù)位置嗎;2. wordpress里,這樣的目錄列表是屬于小工具還是啥?3. 常量在外面不加引號(hào)會(huì)報(bào)錯(cuò)。4. mysql federated引擎無(wú)法開(kāi)啟5. 百度地圖 - Android app中準(zhǔn)備接入地圖sdk,百度VS高德哪個(gè)好一點(diǎn)?6. 我的怎么不顯示啊,話說(shuō)有沒(méi)有QQ群什么的7. sublime text3安裝package control失敗8. python 3.4 error: Microsoft Visual C++ 10.0 is required9. android - Genymotion 微信閃退 not find plugin.location_google.GoogleProxyUI10. MySQL 使用 group by 之后然后 IFNULL(COUNT(*),0) 為什么還是會(huì)獲得 null
