3

If i click the a element "Link1" e.target in the function is the node Link1. I want to know in what index this node is in the ul children in this case i want indexOf to return 0 because Link1 is on position 0, and i i click 2 i want it to be 1.

HTML

<div class="link">
    <ul>
       <li><a>Link1</a></li>
       <li><a>Link2</a></li>
    </ul>
</div>

JAVASCRIPT

self.query('.link').forEach(function(linkNode, flikIndex, flikArr) { 
    dojo.query(linkNode, 'click', function(e) {
        var t = e.target; //If i click Link1 this is Link1 and if i click Link2 and so on. 
        var parent = t.parentNode; //Contains the parent to my a in this case li 
        var ancestor = t.parentNode.parentNode.childNodes; //Containes 2 li 
        var index = Array.prototype.indexOf.call(parent, ancestor); //Return -1 but i want it to return 0 because Link1 is on place [0] in the array.             

    }
}

Please help me get the right index

4

2 回答 2

7
var index = Array.prototype.indexOf.call(parent, ancestor);
//                                       ^ Array ^ Element in the array

所以你想要这个:

var index = Array.prototype.indexOf.call(ancestor, parent);

因为ancestor是包含parent.

于 2013-06-18T11:26:08.097 回答
1

尝试这个:

let nodes = Array.from( parent.closest('ul').children);
let index = nodes.indexOf(li);

当我们使用 NodeList 时,使用这种方法获取 li 的索引可能会很棘手:

var ancestor = t.parentNode.parentNode.childNodes; 
var index = Array.prototype.indexOf.call(ancestor, parent);

如果我们在 lis 中有文本,那么这些也被认为是 childNodes,因此返回的 li 的索引将是它在 nodeList 中的索引,它包含其他子节点,例如文本,而不仅仅是其他 lis。因此,如果您只对 li 相对于 ul 中其他 lis 的位置感兴趣,您可能无法获得所需的结果

于 2021-03-10T09:20:46.557 回答