使用 jQuery 隐藏动态类的所有实例,但第一个实例除外



当我知道类名时,我知道如何隐藏除类的第一个实例之外的所有实例,但是当类是动态的时,如何做到这一点。例如:

<div class="staticcontainername">
  <div class="variable"></div> <!-- This should show -->
  <div class="variable"></div>
  <div class="variable"></div>
  <div class="variable2"></div> <!-- This should show -->
  <div class="variable2"></div>
  <div class="variable3"></div> <!-- This should show -->
  <div class="variable3"></div>
  <div class="variable3"></div>
</div>

每 3 个div 中只有第一个应该可见,无论该类变成什么或存在多少项。

使用 Javascript

您可以迭代它们并将该类与前一个类进行比较。只有在类 matc 完全有效的情况下才能工作,所以如果你有一个带有额外类的div,那将被视为"不同"。

$(function() {
  var previousClass;
  $('.staticcontainername div').each(function(index) {
    // loop trough all elements in the container and get the class of the current element
    var currentClass = $(this).attr('class');
    // compare the elements class with the previous one. 
    // if it matches, hide it
    if (currentClass === previousClass) {
      $(this).hide();
    }
    // before we go to the next element, update the previousClass 
    // so we can compare it in the next iteration
    previousClass = currentClass;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div class="staticcontainername">
  <div class="variable">1</div>
  <!-- This should show -->
  <div class="variable">2</div>
  <div class="variable">3</div>
  <div class="variable2">1</div>
  <!-- This should show -->
  <div class="variable2">2</div>
  <div class="variable3">1</div>
  <!-- This should show -->
  <div class="variable3">2</div>
  <div class="variable3">3</div>
</div>

纯 CSS

如果您知道可能出现的类,则可以使用 CSS 仅显示第一个类。正如本回答所指出的,没有"一流"这样的选择器。但是,提供了一个很好的解决方法,我们可以针对这种情况进行更改。

.staticcontainername>.variable~.variable,
.staticcontainername>.variable2~.variable2,
.staticcontainername>.variable3~.variable3 {
  display: none;
}
<div class="staticcontainername">
  <div class="variable">1</div>
  <!-- This should show -->
  <div class="variable">2</div>
  <div class="variable">3</div>
  <div class="variable2">1</div>
  <!-- This should show -->
  <div class="variable2">2</div>
  <div class="variable3">1</div>
  <!-- This should show -->
  <div class="variable3">2</div>
  <div class="variable3">3</div>
</div>

最新更新