gpt4 book ai didi

javascript - 使用 jQuery .each 仅重复前 5 个元素

转载 作者:行者123 更新时间:2023-12-01 00:44:29 25 4
gpt4 key购买 nike

有人知道如何使用 jQuery 的 each 仅重复前 5 个元素吗?

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

最佳答案

来自documentation :

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

此外,同一个文档还提到了您给 .each 的回调:

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

所以尝试这样的事情:

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

因此,在第五次执行循环后(index 将等于 4),循环将停止。请注意,需要使用此n-1 逻辑,因为您在评估中断条件之前执行循环体。

$(".kltat").each(function(index, element) {
$(element).css('color', 'red');
return index < 4;
});
<script src="https://ajax.googleapis.com/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>

关于javascript - 使用 jQuery .each 仅重复前 5 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27748597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com