0

I've been trying for a while to get this to work, but I can't find a solution that works the way I need.

I'm using zepto.js and what I need to do is get a list of posts from a feed and loop through them. I've got it all working fine apart from posts which don't have a thumbnail. The way I am passing the articles over leaves an empty img tag if the thumbnail is not present.

Here is my code:

function get_articles(feed) {
  $.getJSON(feed, function(data) {
    $.each(data.articles, function(i, field) {
      articles += "<li class='article' id='article-"+field.id+"'><a href='story.html?  aid="+field.id+"'><img src='"+field.thumb+"' class='thumb' /><h3 class='headline'>"+field.headline+"</h3></a></li>"
    })
    $("ul#channel").html(articles)
  })
}

I have tried other methods but I can't seem to find one that doesn't loop the ul or pass multiple loops into one li.

I know I'm probably being stupid, but I've hit a wall. Any pointers will be much appreciated.

Bunkered
  • 309
  • 1
  • 3
  • 12

2 Answers2

1

Use a simple if..else statement

if (field.thumb != "")
{
    articles += "<li class='article' id='article-"+field.id+"'><a href='story.html?  aid="+field.id+"'><img src='"+field.thumb+"' class='thumb' /><h3 class='headline'>"+field.headline+"</h3></a></li>";
}
else
{
    articles += "<li class='article' id='article-"+field.id+"'><a href='story.html?  aid="+field.id+"'><h3 class='headline'>"+field.headline+"</h3></a></li>";
}
slash197
  • 9,028
  • 6
  • 41
  • 70
  • Thanks slash197. I knew it would be simple. I was thinking about the if around the field.thumb, didn't think about just putting around the articles loop. – Bunkered Jun 21 '12 at 08:24
1

If you do not wish to render those elements at all if they don't have thumbnails, you can use map to filter out those elements:

function get_articles(feed) {
  $.getJSON(feed, function(data) {
    var validArticles = $.map(data.articles, function (item, index) {
        if (item.thumb) {
            return item;
        }
    });

    $.each(validArticles, function(i, field) {
      articles += "<li class='article' id='article-"+field.id+"'><a href='story.html?  aid="+field.id+"'><img src='"+field.thumb+"' class='thumb' /><h3 class='headline'>"+field.headline+"</h3></a></li>"
    });

    $("ul#channel").html(articles);
  })
}
Eli
  • 17,397
  • 4
  • 36
  • 49
  • Thanks for the answer, I do wish to render them on this occasion, but I can definitely see 'map' coming in useful further down the line. – Bunkered Jun 21 '12 at 08:28