我试图检查javascript(data [index])中是否有未定义的内容,如果是,则显示警告。但是,它似乎没有打击。
我试过了:
if(data[index]){ }
我试过了:
if (typeof(jsVar) == 'undefined') { }
然而,它们似乎都不起作用,我得到了:
Uncaught ReferenceError: index is not defined
完整代码:
function myAlerts(data)
{
$("#alertsListMissingPets").empty();
$.mobile.loading( 'hide', { theme: "b", text: "Loading", textonly: false});
if(data[index].Name){
$.each(data, function(index) {
console.log(data[index].LostDate)
$("#alertsListMissingPets").append(" <li><a data-lostid='"+ data[index].LostKey + "' data-custom='"+ data[index].AnimalKey + "' href=\"#\">"+ data[index].Name + " <span class=\"ui-li-count\">"+ data[index].Distance + "</span></a></li>");
});
$("#alertsListMissingPets").listview('refresh');
} else {
function alertDismissed() {
$.mobile.changePage("#mainpage");
}
navigator.notification.alert('No missing pets in your area!', alertDismissed, 'Good News', 'Okay' );
}
}
答案 0 :(得分:1)
显然,index
未定义的错误状态。看看你的代码:
if(data[index].Name){ //Check something with index here
$.each(data, function(index) { //Define index here
您不能在循环外使用index
...
答案 1 :(得分:0)
从错误索引变量可以看出未定义。 您应该执行以下操作
typeof(index) == 'undefined'
或
typeof(index) != 'undefined'
答案 2 :(得分:0)
正如其他海报的其他答案/评论中所述,您使用$ .each和数据[索引]定义并不正确。试试这个(未经测试):
function myAlerts(data)
{
$("#alertsListMissingPets").empty();
$.mobile.loading( 'hide', { theme: "b", text: "Loading", textonly: false});
if(data.length > 0) {
$.each(data, function(value) { //index isn't needed based on your code
$("#alertsListMissingPets").append(" <li><a data-lostid='"+
value.LostKey + "' data-custom='"+
value.AnimalKey + "' href=\"#\">"+ value.Name +
"<span class=\"ui-li-count\">"+ value.Distance +
"</span></a></li>");
});
$("#alertsListMissingPets").listview('refresh');
} else {
navigator.notification.alert('No missing pets in your area!', alertDismissed, 'Good News', 'Okay' );
}
}
//moved this out of your else clause for aesthetics
function alertDismissed() {
$.mobile.changePage("#mainpage");
}