使用 jquery 每个函数设置最大计数

Setting a max count with jquery each function

我使用以下代码从 RSS 提要中检索项目:

    function loadData()
    {
        $(xml).find("item").each(function ()
        {
            var title = $(this).find("title").text();
            var description = $(this).find("description").text();
            var linkUrl = $(this).find("guid").text();
            var link = "<br/>" + "<a href='" + linkUrl + "'class='rssLink button-color' target='_blank'>Read More</a>";
            //$('#feedContainer').append('<article id=' + "'rss-item'>" + '<h3>' + title + '</h3><p>' + description + link + '</p>');
            $('#feedContainer').append('<article id=' + "'rss-item'>" + '<h3><a href="' + linkUrl + '">' + title + '</a></h3><p>' + description + '</p>');
        });
    }

但是,问题是 Feed 太长了,我不确定如何才能只显示一定数量的项目。我怎样才能设置要显示的最大项目数?

尝试使用计数器:

var max = 100;
$(xml).find("item").each(function (i) {
   // i --> zero based counter
   if (i < max) {
      // Do your stuff
   } else {
     return false;
   }
});

示例

var max = 5;
$('li').each(function(i) {
  if (i < max) {
    $(this).css('color', 'red');
  } else {
     return false;
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>Test</li>
  <li>Test</li>
  <li>Test</li>
  <li>Test</li>
  <li>Test</li>
  <li>Test</li>
  <li>Test</li>
  <li>Test</li>
  <li>Test</li>
  <li>Test</li>
</ul>

您可以尝试对其进行切片以减少迭代次数。

$(xml).find("item").slice(0, 50).each(function () {...