35

我正处于 .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'...
4

1 回答 1

74

你需要的是context。使用上下文,选择器将只查找上下文的子元素(在这种情况下this)。

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

jsFiddle 演示

这与以下内容基本相同:

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

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

$(this).children(':nth-child(2)').attr('id');
于 2011-05-12T19:39:53.723 回答