jQuery.each 问题

发布于 2024-08-19 10:19:09 字数 117 浏览 7 评论 0原文

是否可以运行 jQuery .each 语句一定次数,而不是针对每个正在迭代的项目?正在迭代的 JSON 是一个last.fm feed,当然,他们经常忽略“限制”请求。我想通过仅运行 .each 语句多次来绕过此错误。

Is it possible to run a jQuery .each statement a certain amount of times rather then for each of the items being iterated? The JSON being iterated is a last.fm feed, and of course, they ignore the "limit" request often. I would like to bypass this error by only running the .each statement so many times.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

一梦浮鱼 2024-08-26 10:19:09
var limit = 5;

$("somelement").each(function(i, val) {
      if(i > limit) return false;
      // do stuff
});

或者

$("somelement:lt(5)").each(function() {
      // do stuff
});
var limit = 5;

$("somelement").each(function(i, val) {
      if(i > limit) return false;
      // do stuff
});

or

$("somelement:lt(5)").each(function() {
      // do stuff
});
寄与心 2024-08-26 10:19:09

不要修改 .each,而是修改选择器以仅选择前“n”个元素。

http://docs.jquery.com/Selectors/lt#index

Rather than modify the .each, modify your selector to select only the first 'n' elements.

http://docs.jquery.com/Selectors/lt#index

梦幻的味道 2024-08-26 10:19:09

最好的解决方案是使用 jQuery 中的 .slice 方法。

var limit = 5;
$("somelement").slice(0, limit).each(function(i, val) {
    // do stuff
});

The best solution is to use the .slice method in jQuery.

var limit = 5;
$("somelement").slice(0, limit).each(function(i, val) {
    // do stuff
});
飘过的浮云 2024-08-26 10:19:09

在循环之前定义一个变量,在每个循环中递增它,然后 if(myvar == 10){return false;}

从每个内部返回“false”
函数完全停止循环
http://docs.jquery.com/Core/each

Define a variable before your loop, increment it within the each, and if(myvar == 10){return false;}

Returning 'false' from within the each
function completely stops the loop
http://docs.jquery.com/Core/each

笑红尘 2024-08-26 10:19:09

当您需要时,从迭代器中返回 false 停止。迭代器的第一个参数是索引(循环数组时)。

Return false out of the iterator when you want to stop. The first parameter to your iterator is the index (when looping through arrays).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文