【问题标题】:get the nth-child number of an element in jquery获取jquery中元素的第n个子编号
【发布时间】:2012-05-11 07:30:13
【问题描述】:

我有一个包含多个“DIV”元素的类,其中包含“p”元素列表。见下文:

<div class="container">
    <p>This is content 1</p>
    <p>This is content 2</p>
    <p>This is content 3</p>
</div>
<div class="container">
    <p>This is content 1</p>
    <p>This is content 2</p>
    <p>This is content 3</p>
</div>

这是我通过悬停调用“p”元素的 jQuery 代码:

$('.container').children('p').hover(function(){
    //get the nth child of p from parent class 'container'
});

如何从其父容器类“容器”中获取元素“p”的第 n 个子编号?

如果你悬停

这是内容 1

它应该触发输出为 1;

【问题讨论】:

  • @ArtemKoshelev 这是错误的方式 - 这个问题是'给定一个元素,告诉我 n',而不是'给定 n,告诉我元素'。
  • @Alnitak 哦,现在我明白了,这给我指出了错误的方式“如何从其父容器类 'container' 中获取元素 'p' 的第 n 个子编号?”跨度>

标签: jquery html


【解决方案1】:

您可以为此使用 jQuery 的 index function。它告诉你给定元素相对于它的兄弟元素的位置:

var index = $(this).index();

Live example | source

索引是从 0 开始的,所以如果您正在寻找一个从 1 开始的索引(例如,第一个是 1 而不是 0),只需添加一个即可:

var index = $(this).index() + 1;

如果您没有使用 jQuery 并且遇到了这个问题和答案(OP 使用的是 jQuery),那么没有它也很简单。 nth-child 只考虑元素,所以:

function findChildIndex(node) {
    var index = 1;                         // nth-child starts with 1 = first child
    // (You could argue that you should throw an exception here if the
    // `node` passed in is not an element [e.g., is a text node etc.]
    // or null.)
    while (node.previousSibling) {
        node = node.previousSibling;
        if (node && node.nodeType === 1) { // 1 = element
            ++index;
        }
    }
    return index;
}

【讨论】:

  • @Alnitak:谢谢,我想 OP 确实 明确表示他们想要1 用于第一个,不是吗?已更新。
【解决方案2】:

使用.index() 方法的无参数版本来查找元素相对于其兄弟元素的位置:

$('.container').children('p').hover(function() {
     var index = $(this).index() + 1;
});

注意.index() 的结果将从零开始,而不是从一开始,因此+ 1

【讨论】:

    【解决方案3】:
    $('.container').children('p').hover(function(){
        //get the nth child of p from parent class 'container'
        var n = 1;
        var child = $(this).parent().find("p:eq("+n+")");
    });
    

    应该可以!

    或者如果你想知道悬停元素的索引:

    $('.container').children('p').each(function(index,element) {
        // use closure to retain index
        $(element).hover(function(index){
            return function() { alert(index); }
        }(index);
    }
    

    http://api.jquery.com/each/

    【讨论】:

    • 是的,它可能是。我不知道.index()。它对性能也没有真正的影响:jsperf.com/index-vs-each。所以我今天学到了一些东西:-)
    • 这不仅仅是性能,还有内存效率。您的版本会为页面上的每个匹配元素创建一个新的闭包。
    • 我知道,但是如果您想将索引存储在某处并且 .index() 不存在,这可能会很有效。另一种选择是将索引存储在元素本身上。但这并不重要:我的选择肯定不是最佳的:-)
    猜你喜欢
    • 2014-06-08
    • 1970-01-01
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    相关资源
    最近更新 更多