Array.prototype.indexOf.call存在问题

时间:2013-06-18 11:23:14

标签: javascript

如果我单击一个元素“Link1”,则该函数中的e.target是节点Link1。我想知道这个节点在ul子节点中的索引是什么,在这种情况下我希望indexOf返回0,因为Link1在0位置,我点击2我希望它是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.             

    }
}

请帮助我获得正确的索引

2 个答案:

答案 0 :(得分:5)

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

所以你想要这个:

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

由于ancestor是包含parent的元素(“数组”)。

答案 1 :(得分: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 中的索引,nodeList 由其他子节点(例如文本)组成,而不仅仅是其他 lis。因此,如果您只对 li 相对于 ul 中其他 lis 的位置感兴趣,则可能无法获得所需的结果