我有一类多个'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>
Run Code Online (Sandbox Code Playgroud)
这是我通过悬停调用'p'元素的jQuery代码:
$('.container').children('p').hover(function(){
//get the nth child of p from parent class 'container'
});
Run Code Online (Sandbox Code Playgroud)
如何从父容器类'container'中获取元素'p'的第n个子编号?
就像你盘旋一样
这是内容1
它应该触发输出为1;
T.J*_*der 71
你可以使用jQuery的index功能.它告诉您给定元素相对于其兄弟姐妹的位置:
var index = $(this).index();
Run Code Online (Sandbox Code Playgroud)
索引是从0开始的,所以如果你正在寻找一个基于1的索引(例如,第一个索引1而不是0),只需添加一个索引:
var index = $(this).index() + 1;
Run Code Online (Sandbox Code Playgroud)
如果你没有使用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;
}
Run Code Online (Sandbox Code Playgroud)
使用方法的无参数版本.index()来查找元素相对于其兄弟的位置:
$('.container').children('p').hover(function() {
var index = $(this).index() + 1;
});
Run Code Online (Sandbox Code Playgroud)
请注意,结果.index()将从零开始,而不是基于一个,因此+ 1