【发布时间】:2016-10-12 21:33:03
【问题描述】:
我试图弄清楚如何获取所选元素的第 n 个子元素的数量。例如,如果我有:
<parent>
<child>a</child>
<child>b</child>
<child>c</child>
<child>d</child>
<child>e</child>
</parent>
如果我有:
$('child').click(function(){
console.log($(this).nthChildOf('parent'));
});
如果我点击c,我喜欢控制台输出3。
感谢您的快速答复。我有一个补充问题。我发现如果我使用:
<parent>
<child onclick="nthOf(this)">a</child>
<child onclick="nthOf(this)">b</child>
<child onclick="nthOf(this)">c</child>
<child onclick="nthOf(this)">d</child>
<child onclick="nthOf(this)">e</child>
</parent>
然后:
function nthOf(e) {
console.log($('parent').index(e));
}
它总是输出 1。
如果我这样做:
function nthOf(e) {
console.log($('parent').index($(e)));
}
它总是输出-1。
我该如何解决这个问题?
【问题讨论】:
-
我想你可以在这个链接里找到你要找的东西jQuery: Get index of element as child relative to parent
-
@SunilKumar 它似乎总是输出
-1。 -
@JamesWayne:你试过了吗?
-
@SunilKumar 在这里:jsfiddle.net/hm6ncfyL
标签: javascript jquery html