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
4 Answers
Reset to default 5From the documentation:
We can break the
$.each()
loop at a particular iteration by making the callback function returnfalse
.
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
版权声明:本文标题:javascript - Reiterate only through the first 5 element using jQuery .each - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741477449a2380968.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论