2012-05-11 150 views
24

我有一个多元'DIV'元素的类,里面是'p'元素的列表。请看下图:得到jquery中元素的第n个子元素号

<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;

谢谢!

+0

链接:http://stackoverflow.com/q/1442925/55209 –

+1

@ArtemKoshelev这是错误的方法 - 这个问题是'给出一个元素,告诉我n',而不是'给出n,告诉我元素'。 – Alnitak

+0

@Alnitak哦,现在我明白了,这指出了我错误的方式“我怎样才能从它的父容器类'容器'中获得元素'p'的第n个子编号?” –

回答

58

你可以使用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; 
} 
+0

你忘了给索引添加1 ... – Alnitak

+0

@Alnitak:谢谢,我想OP *确实*表示他们希望第一个'1',不是吗?更新。 –

+0

最近downvoter请分享一些有用的反馈?为什么你觉得这个答案对于使用downvote按钮的术语“没用”? (尤其是OP显然是这样的。) –

5

使用.index()方法的无参数的版本找到元素相对于其同级的位置:

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

注意的结果.index()将基于零,而不是一个,因此+ 1

-1
$('.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/

+4

哇,这是复杂的... – Alnitak

+0

是的,它可能是。我不知道.index()。它在性能上并没有真正的改变:http://jsperf.com/index-vs-each。所以我今天学到了一些东西:-) –

+1

这不仅仅是性能,它还是内存效率。您的版本为页面上的每个匹配元素创建一个新的闭包。 – Alnitak