gpt4 book ai didi

jquery 每个只输出 JSON 的第一次迭代

转载 作者:行者123 更新时间:2023-12-01 01:10:26 24 4
gpt4 key购买 nike

使用此代码:

$.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:

http://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user=benhowdle89&api_key=b25b959554ed76058ac220b7b2e0a026&format=json

出于某种原因,只有第一次迭代(?)获得输出!

jSFiddle链接:http://jsfiddle.net/MS3Gu/

最佳答案

可能是因为在第二次迭代中,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] 正在尝试在 undefined 上查找 3 属性。

要解决这个问题,您可以测试每个深度级别以确保属性存在。

if( item.image && item.image[3] && item.image[3]['#text'] ) { 
var txt = item.image[3]['#text'];
} else {
var txt = '';
}

关于jquery 每个只输出 JSON 的第一次迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7139325/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com