JS event delegation issue
大家讲道理
大家讲道理 2017-06-08 11:03:05
0
1
542

<!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?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(1)
習慣沉默

Convert

children to Array and then call indexOf directly. (Without considering compatibility...)

<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))
}

Here is an example

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!