【问题标题】:Is there a way to combine $(this) with :nth-child?有没有办法将 $(this) 与 :nth-child 结合起来?
【发布时间】:2011-08-24 10:01:50
【问题描述】:

我正处于 .each 迭代的中间,想为 each 调用第二个或第三个孩子。但无法使其工作。

alert($(this + ' :nth-child(2)').attr('id'));

我能想到的唯一选择是像这样可怕的愚蠢:

 $(this).children(':first').next().attr('id', 'ddParam' + newCount);
 $(this).children(':first').next().next().attr('id', 'txt' + newCount);
 $(this).children(':first').next().next().next().attr('id'...

【问题讨论】:

  • 你试过$(this).find(':nth-child(2)')吗?
  • 我没有,但现在我有了,但没有产生任何结果.. 谢谢
  • 我的错 - 哈哈...在我的情况下,孩子 #2 没有 ID(因此返回空白)

标签: jquery jquery-selectors dom-traversal


【解决方案1】:

您需要的是context。使用上下文,选择器将只查找上下文的子元素(在本例中为 this)。

$(':nth-child(2)', this).attr('id');

jsFiddle Demo

这与:

$(this).find(':nth-child(2)').attr('id');

如果你只需要直系子代,而不是每个后代,你应该使用.children():

$(this).children(':nth-child(2)').attr('id');

【讨论】:

  • alert($(':nth-child(1)', $(this)).attr('id')); -- 谢谢,但这对我没有任何意义……有什么想法吗?
  • @toddv 哦,我有一个错误,已修复。我添加了一个 jsFiddle 让你测试一下。
  • 哎呀..我的孩子 #2 没有 id - 因此是一个空白弹出窗口 --- 对不起。感谢您的回答!
猜你喜欢
  • 2015-04-05
  • 1970-01-01
  • 2013-12-28
  • 1970-01-01
  • 2021-07-28
  • 2013-09-15
  • 2017-12-14
  • 2014-05-09
  • 1970-01-01
相关资源
最近更新 更多