jQuery 有没有办法将 $(this) 与 :nth-child 结合起来?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5983471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to combine $(this) with :nth-child?
提问by Todd Vance
I'm in the middle of an .each iteration and wanted to call out the 2nd or 3rd child for the each..but cant make it work.
我正处于 .each 迭代的中间,并想为 each 调用第二个或第三个孩子......但无法使其工作。
alert($(this + ' :nth-child(2)').attr('id'));
My only option that I can think of is something terrible goofy like this:
我能想到的唯一选择是像这样可怕的愚蠢的事情:
$(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'...
回答by kapa
What you need is context. With context, the selector will only look for elements that are the children of the context (in this case this
).
您需要的是context。使用上下文,选择器将只查找作为上下文子元素的元素(在本例中为this
)。
$(':nth-child(2)', this).attr('id');
This is basically the same as:
这与以下内容基本相同:
$(this).find(':nth-child(2)').attr('id');
If you only need the direct children, not every descendant, you should use .children()
:
如果您只需要直接的孩子,而不是每个后代,您应该使用.children()
:
$(this).children(':nth-child(2)').attr('id');