在jQuery中有一个名为first-child
的选择器。它从匹配的元素中选择第一个孩子 。但是,如果我使用first-of-type
而不是first-child
,它也可以正常工作。所以我只是想知道,有什么区别?jQuery中两个选择器之间的区别
$(function(){
//$('li :first-child').text('some text');
$('li :first-of-type').text('some text');
});
在jQuery中有一个名为first-child
的选择器。它从匹配的元素中选择第一个孩子 。但是,如果我使用first-of-type
而不是first-child
,它也可以正常工作。所以我只是想知道,有什么区别?jQuery中两个选择器之间的区别
$(function(){
//$('li :first-child').text('some text');
$('li :first-of-type').text('some text');
});
刚刚看过的文档(:first-of-type
和:first-child
):
:first-child
选择是他们的父母的第一个孩子的所有元素。
:first-of-type
选择属于同一元素名称的兄弟姐妹中的第一所有元素。
的:first-of-type
选择器将之中一组的兄弟姐妹的给定名称(例如span
,a
等)的第一个元素相匹配。你的榜样将匹配:
<li>
<span>Matches this span</span> <!-- First span amongst siblings -->
<a>Matches this a</span> <!-- First a amongst siblings -->
<a>Doesn't match this one</span> <!-- Second a amongst siblings -->
</li>
的:first-child
选择将只匹配父母的第一个孩子:
<li>
<span>Matches this span</span> <!-- First child of parent -->
<a>Doesn't match this</span> <!-- Second child of parent -->
<a>Nor this</span> <!-- Third child of parent -->
</li>
好的。现在我明白了。感谢所有例子。 –
你真的应该只是阅读文档。 – Archer
好的。我阅读文档,但没有得到清晰的图片。所以我只是在这里发布。现在我有一些例子,所以我的疑问很清楚。 –