search

Home  >  Q&A  >  body text

javascript - 当事件触发的时候如何知道这个li是其父辈ul的第几个子元素?

当事件触发的时候如何知道这个li是其父辈ul的第几个子元素?

PHP中文网PHP中文网2816 days ago365

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-04-10 14:40:09

    jq: xx.index()
    raw js:

    var prev = xx.previousSibling,
        index = 1;
    while(prev){
        if(prev.nodeType!=1){
            prev = prev.previousSibling;
            continue;
        } else{
            prev = prev.previousSibling;
            index++;
        }
    }
    

    li属于ul的第index个元素。


    举个例子:

    <ul>
        <li>123</li>
        <li id="demo">234</li>
        <li>345</li>
    </ul>
    <script>
    document.getElementById("demo").onclick = function(event){
        var event = event || window.event,
            e = event.target || event.srcElement,
            prev = e.previousSibling,
            index = 1;
        while(prev){
            if(prev.nodeType!=1){
            prev = prev.previousSibling;
                continue;
            } else {
            prev = prev.previousSibling;
                index++;
            }
        }
        console.log(index);  // 输出2
    }
    </script>
    

    reply
    0
  • PHPz

    PHPz2017-04-10 14:40:09

    var arr = event.target.parentElement.children;
    for(var i=0;i<arr.length;i++) {
        if(event.target == arr[i]) 
            console.log(i)
    }
    

    额,有点傻,或许该给li加个data-index属性?
    event.target.index

    reply
    0
  • Cancelreply