2011-08-30 198 views
5

採取以下HTML例如:jQuery +如何只選擇每個元素的第一個實例?

<h1>Level 1 Header</h1> 
<h1>My Second Level 1 Header</h1> 
<h1>And a third for kicks</h1> 

<h2>Level 2 Header</h2> 
<h2>2nd Level 2 Header</h2> 

<p>Here is a paragraph.</p> 
<p>Here is a paragraph number 2.</p> 
<p>And paragraph number 3.</p> 

<ul> 
<li>list item 1<li> 
<li>list item 2<li> 
<li>list item 3<li> 
<li>list item 4<li> 
</ul> 

我怎麼可以只選擇每個元素的第一個實例?

我在尋找隱藏所有,每個元素的「第一個」的例外。

在此先感謝!

回答

7

你應該能夠做這樣的事情:

$('h1:first,h2:first,p:first,li:first') 

選擇每一個設置成一個jQuery集合的第一個元素。

+0

很好,謝謝。我希望幾乎有一個功能,我可以寫: 1 - 這個容器中有多少個元素? 2 - 現在我們知道有多少個元素,從選擇過濾每個第一個實例。 我在這個答案中看到的問題,我可以長時間作爲一個表達式,我想也許有腳本來檢查文檔中的內容的方式,而不是指定每個文檔。 感謝您的迴應! –

0

我不知道該怎麼隱含做到這一點,但它很容易選擇明確的第一個元素:

$("h1:first").show(); 

要隱藏所有,但第一:

$("h1:gt(0)").hide(); 

而且,捎帶關TEJS的:

$("h1:gt(0),h2:gt(0),p:gt(0),li:gt(0)") 
0

用於Li情況:

// hide all li and then show the first one 
$('ul li').hide().filter(':lt(1)').show(); 

其他的人:

$('h1:first'); 

$('h2:first'); 

$('p:first'); 
2

爲了獲得最佳性能,避免不規範的選擇,因爲他們將迫使滋滋聲選擇發動機進入較慢的非querySelectorAll代碼分支。非標準選擇的例子可以在這裏找到:http://api.jquery.com/category/selectors/(查找以開頭的選擇「:」)

考慮到這一點,你可以應用策略,您的使用情況如下:

$("h1").hide().eq(0).show(); 

$("h2").hide().eq(0).show(); 

$("p").hide().eq(0).show(); 

$("ul li").hide().eq(0).show(); 

爲了提高性能,使用addClass()/ removeClass()替換hide()/ show(),addClass()/ removeClass()添加並刪除定義狀態更改的類。

爲了獲得更大的性能提升,使用方法:第一胎時/儘可能:http://www.w3.org/TR/CSS2/selector.html#first-child

活生生的例子:http://jsfiddle.net/rwaldron/w4Wz4/

相關問題