假设我们有两个具有相同类名的元素,例如 ."test".
要获得它们中的每一个并按照我的意愿操纵它们,我可以使用类似的东西
$(".test:nth-child(1)")
第一个和
$(".test:nth-child(2)")
第二个
如果我使用 replaceWith
将第一个子元素替换为具有不同类名的不同元素,那么逻辑上将只有一个 .test
类的子元素
然后,如果我使用 $(".test:nth-child(1)")
,我应该得到第二个,因为之前的第一个已被更改。对吧?
但我没有..
现在我只有一个元素带有这个类名 the
$(".test")
与 $(".test:nth-child(1)")
不一样吗??
在我的代码中我必须使用 nth-child 因为很多子元素是动态添加的..
最佳答案
没有。 :nth-child
并不意味着“匹配此选择器其余部分的第 n 个”,它的字面意思是“其父项的第 n 个子项”。 jQuery 有一个 :eq
扩展意味着“这个选择器的其余部分的第 n 个匹配”,但这是 jQuery 特有的完全不同的东西,而不是 CSS 的东西。
Re :nth-child
: 这是一个示例,其中 .foo
和 .foo:nth-child(1)
将找不到同样的事情:
<div>
<div></div>
<div class="foo">abc</div>
</div>
那里,.foo
匹配一个元素,但 .foo:nth-child(1)
不匹配。唯一的 .foo
也不是其父项中的第一个子项。请记住,当您组合选择器的各个部分时,就是在它们之间说“AND”。就像 img.foo
意思是“一个带有标签 img
和类 foo
的元素”,.foo:nth-child(1 )
表示“具有类 foo
且是其父元素中的第一个子元素的元素。”
实例:
.foo {
text-transform: uppercase;
}
.foo:nth-child(1) {
border: 1px solid black;
}
<div>
<div></div>
<div class="foo">abc</div>
</div>
<p>Notice that <code>.foo</code> finds an element (the text has been transformed to upper case), but <code>.foo:nth-child(1)</code> does not (there's no border around it). The <code>.foo</code> is not also the first child in its parent.</p>
CSS 中没有“nth of class”。 (有 :nth-of-type
,它与标记类型有关,与类无关。)而且,同样,jQuery-only :eq
。
关于javascript - 如果DOM中只有一个,类的第n个子(1)是否与类本身具有相同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45054547/