我是 jquery 的初学者,所以我可能不会理解太多高级的东西,但问题是:当我尝试选择 nth-child(1)
时,它按预期选择了第一个(我知道我可以使用第一个 child ,但我不喜欢它)。但是,如果它更改为 nth-child(2)
,则不会选择任何内容。 nth-child(3)
选择 Something2
,nth-child(5)
选择 something3
。这对我来说太过分了!
<div id="navigation">
<a href="#">Something</a> <br />
<a href="#">Something2</a> <br />
<a href="#">Something3</a> <br />
</div>
<script>
$('#navigation').find(">:nth-child(1)").css("font-weight", "bold");
</script>
最佳答案
:nth-child(1)
应该选择第二个元素,因为您传入的索引是从零开始的。
问题是您的选择器包含了 <br />
标签,这不是预期的(从我的角度来看)。
HTML:
<div id="navigation">
<a href="#">Something</a> <br />
<a href="#">Something2</a> <br />
<a href="#">Something3</a> <br />
</div>
JavaScript:
$('#navigation').children().not('br').eq(1).css("font-weight", "bold");
关于jQuery nth-child 选择器跳过数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13785319/