JQuery不是第一个子选择器

问题描述 投票:29回答:3

我有以下标记:

<div class="feed-item">
  <div class="date-header">2012-06-03</div>
</div>
<div class="feed-item">
  <div class="todo">Todo</div>
</div>
<div class="feed-item">
  <div class="meeting">meeting</div>
</div>

我想只显示不同类名的div,例如class =“todo”并保持“date-header”可见。我有以下javascript“

$('.feed-cluster,.feed-item-container').not('div:first.date-header').not(className).slideUp(speed, function(){
      $('.feed-cluster' + className + ',.feed-item-container' + className).slideDown(speed);
});

一切正常,除了我试图排除类名为date-header的第一个孩子的位置:

.not('div:first.date-header')

有人可以建议替代方案吗?

javascript jquery jquery-selectors
3个回答
55
投票
$('div.date-header').slice(1);

应该这样做。

slice是最快的功能!

因为:首先是jQuery扩展而不是CSS规范的一部分,查询使用:首先不能利用本机DOM querySelectorAll()方法提供的性能提升。

替代方式,仍然使用querySelectorAll功能:

$('div.date-header').not(':first');

24
投票

.not('div:first.date-header')应该是.not('.date-header:first')


5
投票

正如@gdoron所说::first不是css规范的一部分,但:not():first-child是。它是所有主流浏览器的supported

所以你也可以使用它来跳过第一个孩子在css中使用jQuery选择器。

$(".child:not(:first-child)").css("background-color", "blue");
div.child {
  background-color: #212121;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="child">
    <p>Im a child of .container</p>
  </div>
  <div class="child">
    <p>Im a child of .container</p>
  </div>
  <div class="child">
    <p>Im a child of .container</p>
  </div>
</div>

旧版浏览器支持


如果您需要支持旧版浏览器,或者您受到:not()选择器的阻碍。您可以使用.child + .child选择器。哪个也行。

$(".child + .child").css("background-color", "blue");
div.child {
  background-color: #212121;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="child">
    <p>Im a child of .container</p>
  </div>
  <div class="child">
    <p>Im a child of .container</p>
  </div>
  <div class="child">
    <p>Im a child of .container</p>
  </div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.