Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: limit number of items

sorry but I'm new in javascrit. I'm writing a simple rss reader, but I want to limit the number of feeds to 5 items, because the my target site can have 100 or more. Here the code:

$("#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");
    });
});

The problem is that when I try to limit the number of items adding var items = $items.length && i < 5; i++); the javascript stop to works. :-(

How to do it?

like image 978
maxlinux2000 Avatar asked Apr 06 '26 23:04

maxlinux2000


1 Answers

var items = $items.length && i < 5; i++); is invalid I think you want to

var items = items.slice(0, 4); is what you want.

https://api.jquery.com/slice/ (as pointed out to me, it's a jQuery object)

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().

Because Javascript is 0-based (starts to count from 0) you want element 0 to 4, in order to get the first 5 elements.

like image 63
online Thomas Avatar answered Apr 09 '26 13:04

online Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!