我有一个看起来像这样的脚本:
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);
}
});
});
}
当&#34; index&#34;时,我在firebug中得到一个未定义或null错误。不等于其中一个索引。我怎么能防止这种情况?显然有if (index == null)
等等,但我不知道如何以正确的方式做到这一点。
答案 0 :(得分: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.cart
,data.cart.shipping
和data.cart.shipping.methods