以增量方式隐藏其他 div

hide other divs in increment

我有一个 parent div 有多个 child div。如果parent里面有5个div,我需要显示全部5个div。如果有 6 个 divs,第 6 个应该被隐藏,所有 1-5 divs 应该仍然可见。如果有 10 个 div,则所有 10 个都应该可见,但如果有 11 个 div 或 12、13 或 14,则应隐藏第 11、12、13 和 14 div,依此类推. div 仅在达到 5、10、15 时才可见,依此类推。我的问题是是否可以使用 jquery?

来做到这一点
<div class="parent">
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test2</div> <!-- this div should be hidden --->
</div>
<div class="parent">
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test2</div> <!-- this div should be hidden --->
    <div>test2</div> <!-- this div should be hidden --->
</div>

$('.parent div').each(function() {
  $(this, '.parent').hide();//hide all div in parent class element
  $index = $(this).index() + 1;//get the index of current div
  $(this).text($index);//change div text to current index
  if ($index % 5 == 0) {//check index if divisible by 5
    $(this).next().prevAll().show();//get next div then show div that has index divisible by 5 and its previous div
  }


})
.parent {
  border: 2px solid black
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test2</div>
  <!-- this div should be hidden --->
</div>
<div class="parent">
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test2</div>
  <!-- this div should be hidden --->
  <div>test2</div>
  <!-- this div should be hidden --->
</div>
<div class="parent">
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test</div>
  <div>test2</div>
  <!-- this div should be hidden --->
  <div>test2</div>
  <!-- this div should be hidden --->
</div>

您可以做一些嵌套循环并将每个 div 的索引与截止值进行比较:

$('.parent').each(function() {
    let $divs = $(this).children('div');

    $divs.each(function() {
        if ($(this).index() >= (Math.floor($divs.length / 5) * 5)) { 
          $(this).hide(); 
        }
    });
});

https://jsfiddle.net/mL43ojrj/

编辑: 虽然我原来的 post 对你的例子有效,否则它会失败。假设我也可以解释一下。

$('.parents').each() - 循环遍历每个 div 和父

的 class

$(this).children('div') - 查找该父项中的所有子项 div。你可以使用 .find(),但是 returns 所有的后代 divs,如果你嵌套更多 divs

就会中断

Math.floor($divs.length / 5) - 计算 5 进入 divs

的次数

* 5 - 如果超过 5 个则乘以 5 div

https://api.jquery.com/children/

https://api.jquery.com/each/