2012-06-05 29 views
0

我有一個腳本,看起來像這樣:jQuery的停止,如果結果爲空或未定義

function bakVormShipping(targetClass) { 
    $.getJSON('http://shop.com/cart/?format=json', function (data) { 
     $.each(data.cart.shipping.methods, function (index, methods) { 
      if (index == "core|2419|36557" || index == "core|2419|36558" || index == "core|2959|31490" || index == "core|2959|31491" || index == "core|2419|36556") { 
       $('<strong/>').html('€' + (+methods.price.price_incl).toFixed(2)).appendTo(targetClass); 
      } 
     }); 
    }); 
} 

我得到一個未定義或爲空錯誤螢火當「指數」並不等於指標之一。我怎樣才能防止呢?很顯然if (index == null)等,但我不知道如何以正確的方式做到這一點。

回答

1

添加未定義的支票上面的if語句

function bakVormShipping(targetClass) { 
$.getJSON('http://shop.com/cart/?format=json', function (data) { 

    $.each(data.cart.shipping.methods, function (index, methods) { 
     if(typeof(index) == "undefined"){ 
      return; 
     } 

     if (index == "core|2419|36557" || index == "core|2419|36558" || index == "core|2959|31490" || index == "core|2959|31491" || index == "core|2419|36556") { 
      $('<strong/>').html('€' + (+methods.price.price_incl).toFixed(2)).appendTo(targetClass); 
     } 

    }); 
}); 

你可能還需要檢查你收到的data對象有你引用的特性,data.cartdata.cart.shippingdata.cart.shipping.methods

+0

是有可能當結果爲空時做「無」?你有什麼含意「有你正在引用的屬性」?這是必要的嗎?我的技能有限,我正在爲我工​​作的公司這樣做,所以任何幫助都非常感謝。無論如何+1 – Meules

+0

如果索引未定義,您可以返回,我編輯了我的答案。如果你知道你的JSON結構沒有改變,你不需要測試這些屬性是否存在。 –

+0

好的thx!現在firebug返回「data.cart.shipping未定義」。也許我還必須在那裏做一個檢查?或者,也許這就是你的意思是「有你正在引用的屬性」? – Meules