簡體   English   中英

jQuery +如何只選擇每個元素的第一個實例?

[英]jQuery + How can I select only the first instance of each element?

以下面的html為例:

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

如何只選擇每個元素的第一個實例?

我想隱藏所有,除了每個元素的“第一”。

提前致謝!

你應該可以做這樣的事情:

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

要將每個集合的第一個元素選擇為jQuery集合。

為了獲得最佳性能,請避免使用非標准選擇器,因為它們會強制Sizzle選擇器引擎進入較慢的非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(),添加和刪除定義display狀態更改的類。

為了進一步提高性能,請盡可能使用:first-child: http//www.w3.org/TR/CSS2/selector.html#first-child

實例: http//jsfiddle.net/rwaldron/w4Wz4/

我不知道如何隱式地執行此操作,但顯式選擇第一個元素非常容易:

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

要隱藏除第一個之外的所有內容

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

而且,捎帶Tejs:

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

對於李案:

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

其他的:

$('h1:first');

$('h2:first');

$('p:first');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM