2012-07-10 44 views
2
[ 
    { 
     "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" 
    }    
] 

在這個例子中,我希望有說,如果這個值是一個條件「視頻」爲此否則,如果值是「圖像」做到這一點......但我似乎無法獲得「視頻」或「圖像」的處理。入住的jQuery的JSON

這是我的函數:

$.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[gallery]\">" + 
        "<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[gallery]\">" + 
        "<img src=" + gallery.video + " alt=" + gallery.title + ">" + 
       "</a>" 
      + "</li>").appendTo(".gallery");  
     } 

    } 
}).error(function() { alert("error"); }); 
+0

你可能想閱讀關於JavaScript語法。以下是'if'和'else'的工作方式:https://developer.mozilla.org/en/JavaScript/Guide/Statements – bokonic 2012-07-10 21:41:29

回答

4

只是gallery.imagegallery.video沒有在任何其他情況將修復它。

您的第一個問題是您使用單一的= - 作業,而不是比較,可能是=====。這使得第一次(圖像)檢查總是成功,還會覆蓋存儲在其中的圖像鏈接,其值爲true

其次,你並不真正需要,除非你做嚴格===與真正的true價值與true比較什麼。只要在條件下使用任何真值。

最後,您實際上是在對象上進行操作。只要jQuery爲您解碼JSON,就不會再與JSON有任何關係。

3
if(gallery.image) { 
//do stuff with it 
} else if(gallery.video) { 
//do stuff with video 
} 
2

檢查如果一個屬性存在的規範的方法 - 用於特定對象被定義 - 是利用操作者typeof和檢查對字符串"undefined",使用標識比較運算符===!==

像這樣:

if (typeof gallery.image !== "undefined") 
    // image code 
else if (typeof gallery.video !== "undefined") 
    // video code 

如果imagegallery的屬性,然後typeof gallery.image永遠是"undefined"。使用身份運算符之一而不是標準相等運算符可以避免由於靜默型轉換造成的問題。

其他方法受許多不一致/問題影響。

您自己的代碼只是爲if測試中的image屬性賦值。