抱歉,我是 javascrit 的新手。 我正在编写一个简单的 rss 阅读器,但我想将提要的数量限制为 5 个项目,因为我的目标站点可以有 100 个或更多。 这里的代码:
$("#mainPage").live("pageinit", function () {
$("h1", this).text(title);
$.get(RSS, {}, function (res, code) {
var xml = $(res);
var items = xml.find("item");
var items = $items.length && i < 5; i++); // here the problem!!
var entry = "";
$.each(items, function (i, v) {
entry = {
title:$(v).find("title").text(),
link:$(v).find("link").text(),
description:$.trim($(v).find("encoded").text()),
category:$.trim($(v).find("category").text()),
date:$(v).find("pubDate").text().substr(0,16),
autor:$(v).find("creator").text()
};
entries.push(entry);
});
var s = '';
$.each(entries, function(i, v) {
s += '<li><a href="#contentPage" class="contentLink" data-entryid="'+i+'">' + v.title + '<br><i>' + v.autor + ' - ' + v.date + '</i></a></li>';
});
$("#linksList").append(s);
$("#linksList").listview("refresh");
});
});
问题是当我尝试限制添加的项目数量时 var items = $items.length && i < 5;我++); javascript 停止工作。 :-(
怎么做?
最佳答案
var items = $items.length && i < 5; i++);
无效我想你想要
var items = items.slice(0, 4);
是你想要的。
https://api.jquery.com/slice/ (正如我所指出的,它是一个 jQuery 对象)
The jQuery object itself behaves much like an array; it has a length property and the elements in the object can be accessed by their numeric indices [0] to [length-1]. Note that a jQuery object is not actually a Javascript Array object, so it does not have all the methods of a true Array object such as join().
因为 Javascript 是基于 0 的(从 0 开始计数),所以您需要元素 0 到 4,以便获得前 5 个元素。
关于javascript:限制项目数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34198682/