獲取當前元素在兄弟元素節點中的索引

weixin_34162695發表於2019-01-15

第一種

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <ul id="ul">
        <li id="item1">item1</li>
        <li id="item2">item2</li>
        <li id="item3">item3</li>
        <li id="item4">item4</li>
        <li id="item5">item5</li>
        <li id="item6">item6</li>
        <li id="item7">item7</li>
        <li id="item8">item8</li>
        <li id="item9">item9</li>
        <li id="item10">item10</li>
    </ul>
    <script>
        var oUl=document.getElementById('ul');
        var lis= oUl.firstElementChild;
        //console.log(lis);
        var item1=document.getElementById('item1');
        var item2=document.getElementById('item2');
        var item3=document.getElementById('item3');
        var item4=document.getElementById('item4');
        var item5=document.getElementById('item5');
        var item6=document.getElementById('item6');
        var item7=document.getElementById('item7');
        var item8=document.getElementById('item8');
        var item9=document.getElementById('item9');
        var item10=document.getElementById('item10');
        
        function getIndex(curEle){
            var ary=[];
            var pre=curEle.previousSibling;
            while(pre){
                if(pre.nodeType===1){
                   ary.push(pre);
                   pre=pre.previousSibling;
                }else{
                   pre=pre.previousSibling; 
                }
            }
            return ary.length;
        }
        console.log(getIndex(item2))
    </script>
</body>
</html>
複製程式碼

第二種方法

  // 獲取當前元素在兄弟節點中的索引
        console.log(getIndex(lis));
        function getIndex(curEle) {
            var arr = [],i = 1;
            arr[0] = curEle;
            var temp = curEle.previousSibling;
            while(temp){
                if (temp.nodeType === 1){
                    arr[i] = temp;
                    i++;
                }
                temp = temp.previousSibling;
            }
            arr = arr.reverse();
            return arr.length-1+1;
        }
    })()
複製程式碼

相關文章