我试图从 last.fm API 附加一些 JSON 数据,
我在几个阶段一直在使用 alert() 来验证 API 是否被正确解析,它是,
这使我得出结论 getElementById().appendChild() 不起作用,下面是我设置的测试页面的 URL:
http://mutant-tractor.com/tabtest.html
代码在这里
function calculateDateAgo(secAgo) {
var agoString, agoRange, agoScaled;
if(secAgo >= (agoRange = 60*60*24))
agoString = (agoScaled = Math.floor(secAgo/agoRange))+" "+(agoScaled>1?"days":"day") + " ago"
else if(secAgo >= (agoRange = 60*60))
agoString = (agoScaled = Math.floor(secAgo/agoRange))+" "+(agoScaled>1?"hours":"hour") + " ago"
else if(secAgo >= (agoRange = 60))
agoString = (agoScaled = Math.floor(secAgo/agoRange))+" "+(agoScaled>1?"minutes":"minute") + " ago"
else if(secAgo >= -60)
agoString = "blastin' out now";
else
agoString = "soon ;)";
return agoString
}
function truncateName(name, l) {
return name.length > l ? name.substr(0,l-2) + "\u2026" : name
}
function lfmRecentTracks(JSONdata) {
try {
var eImg, eLink, eSpan, divTag, eWrapper;
var oTracks = new Array().concat(JSONdata.recenttracks.track);
for (var i = 0; i [lessthanhere] oTracks.length; i++) {
//insert track link
spanTag = document.createElement("span");
spanTag.className = "lfmTrackInfoCell tabslider";
eLink = document.createElement("a");
eLink.appendChild(document.createTextNode( truncateName(oTracks[i].name, 25) ));
//alert(truncateName(oTracks[i].name, 25));
spanTag.appendChild(eLink);
eLink.href = oTracks[i].url;
//alert(oTracks[i].url);
eLink.target = "new";
eLink.className = "lfmTrackTitle";
document.body.appendChild(spanTag);
//insert artist name
eSpan = document.createElement("span");
eSpan.appendChild(document.createTextNode(truncateName(oTracks[i].artist["#text"], 22) ));
//alert(truncateName(oTracks[i].artist["#text"], 22));
eSpan.className = "lfmTrackArtist";
document.body.appendChild(eSpan);
//insert date
eSpan = document.createElement("span");
spanTag.appendChild(eSpan);
eSpan.appendChild(document.createTextNode( (typeof oTracks[i].date=="undefined"?"now playing":calculateDateAgo(new Date().getTime()/1000 - oTracks[i].date.uts)) ));
//alert((typeof oTracks[i].date=="undefined"?"now playing":calculateDateAgo(new Date().getTime()/1000 - oTracks[i].date.uts)));
eSpan.className = "lfmTrackDate";
document.body.appendChild(eSpan);
}
} catch(e) {}
}
它工作的唯一方法是使用 document.body.appendChild()
如果这有什么不同,我会在头脑中调用脚本吗?
我试图将它们附加到的 div 是 4 个不同的 div,即在 for 循环中,每个循环都需要引用不同的元素,
提前致谢!迈尔斯