javascript - 当事件触发的时候如何知道这个li是其父辈ul的第几个子元素?
PHP中文网
PHP中文网 2017-04-10 14:38:09
0
2
369

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

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(2)
巴扎黑

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>
PHPzhong
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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template