【发布时间】:2015-03-31 21:10:16
【问题描述】:
我正在访问以下 JSON 数据:
http://veratech.co.nz/blog/?json=1
当我尝试访问位于下面代码第 4 行的数组中的“url”属性时,我收到一个未定义的错误。即使它会出现在 console.log(第 13 行)中,带有 console.log(val.attachments[0].url);。
代码如下:
$.each(data.posts, function(index, val){
output += '<li>';
output += '<a href="#blogpost" onclick = showPost(' + val.id + ')">';
output += '<img src="' + val.attachments[0].url + '" alt="">';
output += '<h3>' + val.title + '</h3>';
//Here we shorten the paragraph to 60 characters.
var str = val.excerpt;
var paraInfo = str.slice(0, 60);
output += '<p>' + paraInfo + '</p>';
//Closing off the the closing html tags
output += '</a>';
output += '</li>';
console.log(val.attachments[0].url);
});//Go through each post
非常感谢您的建议
【问题讨论】:
-
JSON 似乎无效
-
您确定它与您在控制台中看到的值相同,而不是上一次迭代中的值吗?如果出现错误,它将停止脚本执行,并且不会再到达 console.log 行。
-
它可以在控制台中正常工作并列出所有 url 数据。正如第 4 行的
-
呃,哪一行准确地显示了错误,具体说了什么?
-
TypeError: val.attachments[0] 未定义
标签: javascript jquery json each