2013-04-18 31 views
1

在jQuery中有一個名爲first-child的選擇器。它從匹配的元素中選擇第一個孩子 。但是,如果我使用first-of-type而不是first-child,它也可以正常工作。所以我只是想知道,有什麼區別?jQuery中兩個選擇器之間的區別

$(function(){ 
    //$('li :first-child').text('some text'); 
    $('li :first-of-type').text('some text'); 
}); 
+0

你真的應該只是閱讀文檔。 – Archer

+0

好的。我閱讀文檔,但沒有得到清晰的圖片。所以我只是在這裏發佈。現在我有一些例子,所以我的疑問很清楚。 –

回答

6

剛剛看過的文檔(:first-of-type:first-child):

:first-child
選擇是他們的父母的第一個孩子的所有元素。

:first-of-type
選擇屬於同一元素名稱的兄弟姐妹中的第一所有元素。

:first-of-type選擇器將之中一組的兄弟姐妹的給定名稱(例如spana等)的第一個元素相匹配。你的榜樣將匹配:

<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> 
+0

好的。現在我明白了。感謝所有例子。 –