[
{
"link" : "images/examples/image-3.png",
"image" : "images/examples/image-3.png",
"title" : "copy"
},
{
"link" : "images/examples/image-3.png",
"video" : "video placeholder",
"title" : "copy"
}
]
In this example, I want to have a condition that says if this value is “video” do this else if value is “image” do this… but I seem to not be able to get handle of “video” or “image”.
This is my function:
$.getJSON("javascripts/media.json", function(data) {
$("<ul class='gallery'></ul>").prependTo("#content");
for (var i=0; i<data.length; i++) {
var gallery = data[i];
//alert(data[1]);
if (gallery.image = true) {
$(
"<li class='image'>" +
"<a class=\"imageLink\" href='" + gallery.link + "' rel=\"lightbox\">" +
"<img src=" + gallery.image + " alt=" + gallery.title + ">" +
"</a>"
+ "</li>").appendTo(".gallery");
}
else if (gallery.video = true) {
$(
"<li class='video'>" +
"<a class=\"videoLink\" href='" + gallery.link + "' rel=\"lightbox\">" +
"<img src=" + gallery.video + " alt=" + gallery.title + ">" +
"</a>"
+ "</li>").appendTo(".gallery");
}
}
}).error(function() { alert("error"); });
Just
gallery.imageandgallery.videowithout anything else in condition will fix it.Your first problem is that you use single
=– assignment, not comparison that would be either==or===. This making first (image) check always succeed and also overwrites image link you store in it with valuetrue.And second, you don’t really need to compare anything with
trueunless you do strict===with realtruevalue. Just use any truthy value in condition by itself.And last, you actually operate on object. As soon as jQuery decoded JSON for you, this no longer have anything to do with JSON.