使用此代码:
$.each(data.toptracks.track, function(index, item){
$('.lastfm').append('<figure class="clearfix"><p><a href="'+item.url+'">'+item.name+'</a>'+item.artist.name+'</p><div class="vinyl"><img class="recordLabel" src="' + item.image[3]['#text'] + '" /></div></figure>');
});
使用此URL查看JSON:
由于某种原因,只有第一次迭代(?)得到输出!
jSFiddle链接:http://jsfiddle.net/MS3Gu/
答案 0 :(得分:3)
可能是因为在第二次迭代中,item
没有image
属性,因此item.image[3]['#text']
会导致其崩溃。
{
"toptracks": {
"track": [{
"name": "Someone Like You",
"duration": "284",
"playcount": "1033",
"mbid": "",
"url": "http:\/\/www.last.fm\/music\/Adele\/_\/Someone+Like+You",
"streamable": {
"#text": "1",
"fulltrack": "0"
},
"artist": {
"name": "Adele",
"mbid": "b0335a95-8a12-4c71-8149-5054ec847d04",
"url": "http:\/\/www.last.fm\/music\/Adele"
},
"image": [{
"#text": "http:\/\/userserve-ak.last.fm\/serve\/34s\/55125087.png",
"size": "small"
},
{
"#text": "http:\/\/userserve-ak.last.fm\/serve\/64s\/55125087.png",
"size": "medium"
},
{
"#text": "http:\/\/userserve-ak.last.fm\/serve\/126\/55125087.png",
"size": "large"
},
{
"#text": "http:\/\/userserve-ak.last.fm\/serve\/300x300\/55125087.png",
"size": "extralarge"
}],
"@attr": {
"rank": "1"
}
},
{
"name": "Somebody To Love Me (ft. Boy George & Miike Snow)",
"duration": "298",
"playcount": "1011",
"mbid": "",
"url": "http:\/\/www.last.fm\/music\/Mark%2BRonson%2B%2526%2BThe%2BBusiness%2BIntl\/_\/Somebody%2BTo%2BLove%2BMe%2B%2528ft.%2BBoy%2BGeorge%2B%2526%2BMiike%2BSnow%2529",
"streamable": {
"#text": "0",
"fulltrack": "0"
},
"artist": {
"name": "Mark Ronson & The Business Intl",
"mbid": "146a66b3-5544-4b7e-9b69-9b53ee30746a",
"url": "http:\/\/www.last.fm\/music\/Mark%2BRonson%2B%2526%2BThe%2BBusiness%2BIntl"
},
/* NO IMAGE PROPERTY */
"@attr": {
"rank": "2"
}
},
// ...
由于没有image
属性,当您执行item.image
时,它会返回undefined
,因此item.image[3]
正在尝试查找3
属性undefined
1}}。
要解决此问题,您可以测试每个深度级别以确保属性存在。
if( item.image && item.image[3] && item.image[3]['#text'] ) {
var txt = item.image[3]['#text'];
} else {
var txt = '';
}
答案 1 :(得分:1)
这是因为该数组中的第二项不包含image[3]
属性。