簡體   English   中英

如何使用jQuery定位第一個div?

[英]how to target the first div with jquery?

我是jquery新手,請耐心等待。 我需要找到一種方法,始終從頁面上出現的具有相同類的每個div系列中獲取第一個div ,以便可以向它們添加一些特定的CSS樣式。 所以從技術上講,我需要類似於CSS中的:first-child

我嘗試使用.first()但是那只能使我從具有該類名稱的第一個“ div”系列中獲得第一個div

例:

<div class="expl">....</div> <!-- need to target this div-->
<div class="expl">....</div>
<div class="expl">....</div>

<h1>....</h1> - this is just an example, we can have any other html tag/content here
<div class="expl">....</div> <!-- and this div-->
<div class="expl">....</div>
<div class="expl">....</div>

<p>....</p>
<div class="expl">....</div> <!-- and this div-->
<div class="expl">....</div>
<div class="expl">....</div>

您可以使用以下CSS選擇器:

*:not(.expl) + .expl

這將針對任何.expl立即是非以下元素.expl元素。 顯然,您可以根據需要使用jQuery,也可以不使用jQuery。

工作實例

嘗試將div集包裝到另一個div中,如下所示:

<div class="exp-wrapper">
  <div class="expl">....</div> <!-- need to target this div-->
  <div class="expl">....</div>
  <div class="expl">....</div>
</div>
<h1>....</h1>
<div class="exp-wrapper">
   <div class="expl">....</div> <!-- and this div-->
   <div class="expl">....</div>
   <div class="expl">....</div>
</div>

<p>....</p>
<div class="exp-wrapper">
   <div class="expl">....</div> <!-- and this div-->
   <div class="expl">....</div>
   <div class="expl">....</div>
</div>

然后,很容易在包裝器中選擇第一個div。

$(".exp-wrapper div:first")

更新:也許是這樣的:

$(".expl:first").add($(":not(.expl)").next(".expl"));

根據Sunyatasattva的CSS答案,等效的jQuery如下(使用JQuery的下一個相鄰選擇器 ):

var theThingsIWant = $(".expl:first").add(":not(.expl) + .expl");

可以在此JsFiddle上看到一個工作示例

分解:

  • $(".expl:first") -查找第一個div
  • .add(":not(.expl) + .expl") -還包括與任何元件expl即將由同級這是與元素前面類expl類。

有關更多詳細信息,請參見https://api.jquery.com/next-adjacent-Selector/

var divs = [$("div.expl").first(),
$("h1").first().next("div.expl").first(),
$("p").first().next("div.expl").first()];

但是,這是一個更加可靠的解決方案。

var selectAfter = function(what,whichIsAfter) {
    return $(what).filter(function() {
        return $(this).prev().not(what).is(whichIsAfter);
    });
}
var divs = selectAfter("div.expl","*").add("div.expl:first");

jsfiddle- http://jsfiddle.net/5gTcC/1/

暫無
暫無

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

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