【问题标题】:Get the number of nth child of a selected element [duplicate]获取所选元素的第n个子元素的数量[重复]
【发布时间】: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。

我该如何解决这个问题?

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

您可以使用.index() 获取其兄弟元素中的元素数。

$('child').click(function(){
  console.log($('child').index( this ) + 1);
});

DEMO

在回复您最近的评论时,我不知道您想要实现什么,但如果那是您想要的,我会给您:D,以便根据您对问题的更新。你的功能应该是...

function nthOf(e) {
  console.log($(e).parent().children().index(e) + 1);
}

DEMO

【讨论】:

  • 请记住,如果 OP 在单击 c 时想要 3,则需要在其中添加 1。也不需要传入this
  • 很好,詹姆斯!我会更新答案。
  • 总是返回:0
  • @shushil 更新代码。
猜你喜欢
  • 2012-03-29
  • 1970-01-01
  • 2020-04-24
  • 2010-10-16
  • 2018-08-07
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
相关资源
最近更新 更多