Home  >  Q&A  >  body text

JS event delegation issue

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

大家讲道理大家讲道理2689 days ago539

reply all(1)I'll reply

  • 習慣沉默

    習慣沉默2017-06-08 11:05:05

    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

    reply
    0
  • Cancelreply