if / else jQuery with JSON

时间:2016-11-05 18:02:07

标签: jquery json if-statement

我的JSON包含一些图片。当他们应该和他们不应该时,我已经让这些照片工作了。借助于jQuery中的if / else。现在我想做的是,如果显示图像,一些文字也会显示。我希望只有在显示图像时才能显示foto。以下代码不起作用。

问题是:我希望foto只显示JSON中的image

var titel = post.titel;
var content = post.content;
var date = post.date;
var author = post.author;
var foto = post.foto
var image = post.image;


  // if a image is going to be displayed
 if (image.length >= 1){
 img = '<img src="/images/' + image+'" alt="image">';
 if (foto.length >= 1){
    renderfoto = foto;
} else{
    renderfoto = "";
}
// else if a image should not be displayed
}else{
img = "";
renderfoto = "";
}

这就是JSON的显示方式。它有效。

var postcontent = '<div class="content-grid-info">'+img+'<div class="post-info"><h1>'+titel+' </h1><h3>Datum: '+date+' Author: '+author+' Photo: '+foto+' </h3><p>'+content+'</p></div></div>';
posts.append(postcontent);

JSON有很多信息,但我会向您展示两种不同的

{
"posts": [{ 
    "titel": "Blogginlägg 14",
    "content": "'Give it a little touch. Give it a little push push. Caress    it, very gentle.'",
    "date": "2016-11-03",
    "author": "Åsa",
    "foto": "Bo Morenius bmbild.se/",
    "image": "post4.jpg"
    },{
    "titel": "Blogginlägg 9",
    "content": "There are no limits here, start out by believing here. (Points at the heart)",
    "date": "2016-11-03",
    "author": "Åsa",
    "image": ""
    }
]
}

2 个答案:

答案 0 :(得分:0)

您需要为要呈现的foto使用与包含post.foto的变量不同的变量(就像您对渲染图像有img一样,并且image用于post.image

var foto = post.foto
var image = post.image;

// if a image is going to be displayed
if (image.length >= 1){
    img = '<img src="/images/' + image+'" alt="image">';
    if (foto.length >= 1){
        renderfoto = foto;
    } else{
        renderfoto = "";
    }
// else if a image should not be displayed
}else{
    img = "";
    renderfoto = "";
}

答案 1 :(得分:0)

我假设你想要显示帖子,如果他们有图像,你想要显示它。

我将您的JSON分配给变量数据,然后遍历posts数组。

data.posts.forEach(function(el) {
  if (el.image) {
    var postcontent = '<div class="content-grid-info">'+el.image+'<div class="post-info"><h1>'+el.titel+' </h1><h3>Datum: '+el.date+' Author: '+el.author+' Photo: '+el.foto+' </h3><p>'+el.content+'</p></div></div>';
  } else {
    var postcontent = '<div class="content-grid-info">'+el.image+'<div class="post-info"><h1>'+el.titel+' </h1><h3>Datum: '+el.date+' Author: '+el.author+' </h3><p>'+el.content+'</p></div></div>';
  }
  posts.append(postcontent);
});

现在您可以创建一个div元素并将其附加到DOM。例如,您可以这样做:

{{1}}