admin管理员组

文章数量:1289423

does anybody know how to reiterate through only the first 5 elements using jQuery's each?

$(".kltat").each(function() {
   // Only do it for the first 5 elements of .kltat class
}

does anybody know how to reiterate through only the first 5 elements using jQuery's each?

$(".kltat").each(function() {
   // Only do it for the first 5 elements of .kltat class
}
Share Improve this question asked Jan 2, 2015 at 21:10 AerodynamikaAerodynamika 8,42318 gold badges91 silver badges149 bronze badges 2
  • 4 you could do a counter and just return after 5 or call slice(0, 5). – Daniel A. White Commented Jan 2, 2015 at 21:11
  • 2 $(".kltat:lt(5)").each(function() { ... – adeneo Commented Jan 2, 2015 at 21:14
Add a ment  | 

4 Answers 4

Reset to default 5

From the documentation:

We can break the $.each() loop at a particular iteration by making the callback function return false.

Furthermore, the same documentation says of the callback you give to .each:

In the case of an array, the callback is passed an array index and a corresponding array value each time.

So try something like this:

$(".kltat").each(function(index, element) {
   // do something
   // ...
   return index < 4;
});

So after you execute the loop on the fifth time (index will equal 4), the loop will stop. Note that using this n-1 logic is needed because you execute the body of the loop before you evaluate the breaking condition.

$(".kltat").each(function(index, element) {
  $(element).css('color', 'red');
  return index < 4;
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="kltat">Item 1</li>
  <li class="kltat">Item 2</li>
  <li class="kltat">Item 3</li>
  <li class="kltat">Item 4</li>
  <li class="kltat">Item 5</li>
  <li class="kltat">Item 6</li>
  <li class="kltat">Item 7</li>
</ul>

You can implement a counter such as this:

var counter = 1;
$(".kltat").each(function() {
   // Only do it for the first 5 elements of .kltat class
   if (counter==5) {
     return false;
   } else {
     counter++;
   }
}

or something of this sort.

How about using .filter():

$(".kltat").filter(function (i) { return i < 5; })
.each(function () {
    // ...
});
$(".kltat").slice(0,5).each(function() {
   // Only do it for the first 5 elements of .kltat class
})

And without jquery:

[].slice.call(document.querySelectorAll('.kltat')).slice(0,5).forEach(function (element) {
    doStuff(element)
})

本文标签: javascriptReiterate only through the first 5 element using jQuery eachStack Overflow