我如何修改jQuery .east(),以便我只得到n个项目,而不是全部



我正在使用jQuery解析XML feed来创建自定义RSS feed。

这是我拥有的:

        var $XML = $(data);
        $XML.find("item").each(function () {
            var $this = $(this),
                item = {
                    title: $this.find("title").text(),
                    link: $this.find("link").text(),
                    description: $this.find("description").text(),
                    pubDate: $this.find("pubDate").text(),
                    author: $this.find("author").text()
                };
            $('#TestFeed').append($('<h2/>').text(item.title));
            $('#TestFeed').append($('<a/>').text(item.link));
            $('#TestFeed').append($('<p/>').text(item.description));
            $('#TestFeed').append($('<p/>').text(item.pubDate));
            $('#TestFeed').append($('<p/>').text(item.author));
        });

我的问题是,我该如何修改它,特别是.each(),以便我只获取最新的3个项目,而不是全部?

对不起,我通过阅读此书来弄清楚这一点。

我对此进行了修改:

<script>
    $.get("https://test.com/feed/", function (data) {
        var $XML = $(data);
        $XML.find("item").each(function (index) {
            var $this = $(this),
                item = {
                    title: $this.find("title").text(),
                    link: $this.find("link").text(),
                    description: $this.find("description").text(),
                    pubDate: $this.find("pubDate").text(),
                    author: $this.find("author").text(),
                };
            $('#TestFeed').append($('<h2/>').text(item.title));
            $('#TestFeed').append($('<a href="' + item.link + '"/>').text(item.link));
            $('#TestFeed').append($('<br/>'));
            $('#TestFeed').append($('<p/>').text(item.description));
            $('#TestFeed').append($('<br/>'));
            $('#TestFeed').append($('<p/>').text(item.pubDate));
            $('#TestFeed').append($('<br/>'));
            $('#TestFeed').append($('<p/>').text(item.author));
            if (index >= 2)
                return false;
        });
    });
</script>

希望将来对某人有所帮助。

最新更新