【问题标题】:which one in the column is this element [closed]列中的哪一个是这个元素[关闭]
【发布时间】:2012-10-20 16:55:25
【问题描述】:

假设我有以下代码:

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

点击时我需要func函数来获取:
1. div的索引,onclick事件被调用的地方。
2.容器中的div总数。

【问题讨论】:

  • 6 票反对,但没有提及原因?我很好奇这个问题有什么问题。
  • 人们无法解析这两个问题的英文,尤其是第1点。
  • 没错,很难说出这里问的是什么。我认为这是一个 DOM 问题(所以我添加了标签)。这有点晚了,但由于问题已经结束,但@oneat,也许你可以尝试澄清你在问什么。我会编辑这个问题,但我不想假设太多。
  • 我假设 OP 想要触发事件的 div 的索引,以及容器中 div 的总数。
  • user1689607 明白了这一点。对不起我的英语不好,我会重新编辑这个问题。

标签: javascript html dom


【解决方案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,并测试nodeType为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);
}

所有这些都假设容器中没有其他元素需要计算在内。如果还有其他人,您需要将它们从计数中过滤掉。

【讨论】:

    【解决方案2】:

    此代码将满足您的需求:

    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

    【讨论】:

      猜你喜欢
      • 2011-05-24
      • 1970-01-01
      • 1970-01-01
      • 2022-06-29
      • 1970-01-01
      • 2021-10-08
      • 2013-01-17
      • 1970-01-01
      • 2021-06-30
      相关资源
      最近更新 更多