获取jquery中元素的第n个子编号
我有一类多个’DIV’元素,里面是’p’元素列表。 见下文:
This is content 1
This is content 2
This is content 3
This is content 1
This is content 2
This is content 3
这是我通过hover调用’p’元素的jquery代码:
$('.container').children('p').hover(function(){ //get the nth child of p from parent class 'container' });
如何从其父容器类’container’中获取元素’p’的第n个子编号?
就像你盘旋一样
这是内容1
它应该触发输出为1;
谢谢!
你可以使用jQuery的index
函数 。 它告诉您给定元素相对于其兄弟姐妹的位置:
var index = $(this).index();
实例 | 资源
索引是从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 [eg, is a text node etc.] // or null.) while (node.previousSibling) { node = node.previousSibling; if (node && node.nodeType === 1) { // 1 = element ++index; } } return index; }
使用.index()
方法的无参数版本来查找元素相对于其兄弟的位置:
$('.container').children('p').hover(function() { var index = $(this).index() + 1; });
请注意, .index()
的结果将从零开始,而不是从一开始,因此为+ 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+")"); });
应该管用!
或者,如果您想知道hover元素的索引:
$('.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/