[英]Uncaught typeerror cannot read property 'image' of undefined with json data
I'm having an 我正在
Uncaught TypeError cannot read property 'image' of undefined
error when calling some Json data. 调用某些Json数据时出错。 My js is the following:
我的js如下:
$.getJSON('/js/data.json', function (json) {
Object.keys(json).forEach(function (country) {
$(".marker." + country.toLowerCase()).on("click", function () {
$("#show").html(
"Image: <img src=" + json[country][0].image + ">" +
"| Description: <h1>" + json[country][0].description) + "</h1>";
});
});
});
and my data.json the following: 和我的data.json如下:
{
"france": {
"image": "img/ausralia.jpg",
"description": "number django 1"
},
"australia": {
"image": "img/ausralia.jpg",
"description": "number django 2"
},
"uk": {
"image": "img/ausralia.jpg",
"description": "number django 3"
}
}
ON click, no data are being display and I'm having that error being display in my console. 单击时,没有数据正在显示,并且我的控制台中正在显示该错误。
The weird thing is that If i call the data like this in my js, the error doesn't appear and everything works correctly. 奇怪的是,如果我在js中调用像这样的数据,则不会出现错误,并且一切正常。 But I need to be able to call the data from an external file.
但是我需要能够从外部文件中调用数据。
var json = {
"France": [{
"image": "img/ausralia.jpg",
"description": "number django 1"
}],
"Australia": [{
"image": "img/ausralia.jpg",
"description": "number django 2"
}],
"uk": [{
"image": "img/ausralia.jpg",
"description": "number django 2ee"
}]
}
Object.keys(json).forEach(function (country) {
$(".marker." + country.toLowerCase()).on("click", function () {
$("#show").html(
"Image: <img src=" + json[country][0].image + ">" +
"| Description: <h1>" + json[country][0].description) + "</h1>";
});
});
Any help will be amazing, I know there is post about this error, but I cant find any solution to make it work ! 任何帮助都将是惊人的,我知道有关于此错误的帖子,但是我找不到任何解决方案来使其正常工作!
Hope it make sense , thanks for your time ! 希望有道理,感谢您的宝贵时间!
Try this, 尝试这个,
Object.keys(json).forEach(function (country) {
if(typeof json[country][0].image !== "undefined" && typeof json[country][0].description !== "undefined" ) {
$(".marker." + country.toLowerCase()).on("click", function () {
$("#show").html( "Image: <img src=" + json[country][0].image + ">" + "| Description: <h1>" + json[country][0].description) + "</h1>";
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.