2012-10-20 23 views
-4

假设下面的代码我有:哪一个列是该元素

<div id="container"> 
<div onclick="func(this)"></div> 
... 
... 
<div onclick="func(this)"></div> 
</div> 

在点击我需要的功能func获得:
1.股利,其中的onclick的指数事件被调用。
2.容器中div的总数。

+1

6个downvotes并没有提到为什么?我很好奇这个问题有什么问题。 – Matthew

+2

人们无法解析这两个问题的英语,特别是第一点。 – bmargulies

+0

确实,很难说出这里提出的问题。我认为这是一个DOM问题(所以我添加了标签)。这有点晚了,但由于问题已经结束,但是@oneat,也许你可以试着澄清你的问题。我会编辑这个问题,但我不想假设太多。 – Matthew

回答

1

假设您的func收到this作为第一个参数,您可以简单地遍历先前的兄弟姐妹,并计算出之前有多少人计算出索引。

为了获得总数,只需从父母处获得.children的计数。

function func(elem) { 
    var idx = 0; 
    var total = elem.parentNode.children.length; 
    // --------v----note the assignment! 
    while (elem = elem.previousElementSibling) { 
     idx++; 
    } 
    console.log("index:", idx, " of:", total); 
} 

如果您需要支持没有.previousElementSibling旧的浏览器,你可以使用.previousSibling和测试的节点类型是1

function func(elem) { 
    var idx = 0; 
    var total = elem.parentNode.children.length; 
    // --------v----note the assignment! 
    while (elem = elem.previousSibling) { 
     if (elem.nodeType === 1) 
      idx++; 
    } 
    console.log("index:", idx, " of:", total); 
} 

所有这些假设没有其他元素在应计数的容器中。如果有其他人,则需要将其过滤掉。

1

该代码会做你需要的东西:

function func(el){ 
    // get the list of all element contained by the parent 
    var list = el.parentElement.children, i; 
    // get the index of the element 
    for (i = 0; i<list.length;i++){ 
     if (list[i] == el) break; 
    } 
    // logging index and total childrencount to console (F12) 
    console.log("children total: "+list.length); 
    console.log("# of element: "+ ++i); 
}​ 

Example

相关问题