How to select next 'n' consecutive element

2019-08-30 09:35发布

问题:

How to select next 'n' consecutive elements on every click using jQuery?

In below example, I want to select the first 4 li elements on first button click, next 4 on 2nd click and next 4 on 3rd Click, upto 'n' numbers.

$(document).ready(function(){
  $(".btn").on('click', function(){
    $("li:nth-child(-n+4)").addClass("selected");
  });
});
.btn{ text-decoration:none; background:blue; color:#fff; padding:5px; border-radius:4px;float:left;}
ul{ list-style:none;float:left;clear:both;}
ul li{ padding:5px;background:#555; color:#fff; float:left; border-radius:2px; margin:2px; }
.selected{ background:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<a class="btn">select next 4 consecutive elements</a>
<ul>
  <li> 1st 4</li>
  <li> 1st 4</li>
  <li> 1st 4</li>
  <li> 1st 4</li>
  <li> 2nd 4</li>
  <li> 2nd 4</li>
  <li> 2nd 4</li>
  <li> 2nd 4</li>
  <li> 3rd 4</li>
  <li> 3rd 4</li>
  <li> 3rd 4</li>
  <li> 3rd 4</li>
</ul>

回答1:

You can create a variable initialized to 0 and increment the variable by 4, use .slice() to select n elements

$(document).ready(function(){
  var n = 0;
  $(".btn").on('click', function(){
    $("li")
    .removeClass("selected")
    .slice(n, n += 4)
    .addClass("selected");
    if (n >= $("li").length) n = 0;
  });
});
.btn{ text-decoration:none; background:blue; color:#fff; padding:5px; border-radius:4px;float:left;}
ul{ list-style:none;float:left;clear:both;}
ul li{ padding:5px;background:#555; color:#fff; float:left; border-radius:2px; margin:2px; }
.selected{ background:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<a class="btn">select next 4 consecutive elements</a>
<ul>
  <li> 1st 4</li>
  <li> 1st 4</li>
  <li> 1st 4</li>
  <li> 1st 4</li>
  <li> 2nd 4</li>
  <li> 2nd 4</li>
  <li> 2nd 4</li>
  <li> 2nd 4</li>
  <li> 3rd 4</li>
  <li> 3rd 4</li>
  <li> 3rd 4</li>
  <li> 3rd 4</li>
</ul>