javascript - JS事件委托问题
问题描述
<!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>
我想问一下,这种用事件委托的方式获取索引的方式,有没有更加简单的方法呢?
问题解答
回答1: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))}
这里有个例子
相关文章:
1. 求救一下,用新版的phpstudy,数据库过段时间会消失是什么情况?2. node.js - Angular-webpack-Starter, 怎么把NodeJS添加进项目里?3. android-studio - android studio自带模拟器中的本地“图库”所对应的路径是什么?4. node.js - yo webapp构建项目时报错了,如图5. javascript - gulp-nodemon 使用重启express 服务器的时候端口被占用6. python 多进程如何调试7. 【python小白】 问关于之初始化一次对象的问题8. java - 微信开发遇到一个 bug。。access_token 有关的9. thinkphp中Controller里面使用Request::File(’image’);10. 人工智能 - python 机器学习 医疗数据 怎么学

网公网安备