获取jQuery中元素的第n个子编号 [英] get the nth-child number of an element in jquery
问题描述
我有一类包含多个"DIV"元素的元素,并且其中包含"p"元素的列表.见下文:
I have a class of multiple 'DIV' elements and inside it are list of 'p' elements. See below:
<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代码:
Here's my jQuery code on calling the 'p' elements through hover:
$('.container').children('p').hover(function(){
//get the nth child of p from parent class 'container'
});
如何从其父容器类容器"中获取元素"p"的第n个子代号?
How can I get the nth child number of the element 'p' from its parent container class 'container'?
就像你悬停一样
这是内容1
This is content 1
应将输出触发为1;
推荐答案
您可以为此使用jQuery的 index
函数 .它会告诉您给定元素相对于其同级元素的位置:
You can use jQuery's index
function for that. It tells you where the given element is relative to its siblings:
var index = $(this).index();
索引是从0开始的,因此,如果您要查找从1开始的索引(例如,第一个是1
而不是0
),只需向其添加一个:
The indexes are 0-based, so if you're looking for a 1-based index (e.g., where the first one is 1
rather than 0
), just add one to it:
var index = $(this).index() + 1;
如果您不使用jQuery并遇到此问题和答案(OP使用jQuery),则没有它也很简单. nth-child
仅考虑元素,因此:
If you're not using jQuery and came across this question and answer (the OP was using jQuery), this is also quite simple to do without it. nth-child
only considers elements, so:
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;
}
这篇关于获取jQuery中元素的第n个子编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!