getElementById().appendChild() 拒绝工作!
我试图从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 循环中每个循环需要引用不同的元素,
提前致谢! 迈尔斯
Im trying to append some JSON data from the last.fm API,
I have been using alert() at several stages to verify the API is being parsed correctly and it is,
This has led me to the conclusion that getElementById().appendChild() doesn't work, below is the URL to the test page I have set up:
http://mutant-tractor.com/tabtest.html
Code here
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) {}
}
The only way it works is by using document.body.appendChild()
I'm calling the script in the head if that makes a difference?
The div I'm trying to attach them to are 4 different divs i.e. in the for loop each loop needs to reference a different element,
Thanks in advance!
Myles
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果文档正文尚未解析,您将无法
getElementById()
。换句话说,您需要在window.onload
函数中运行代码,或者将其放在正文的最底部。另外,在测试时删除
try/catch
,它只会隐藏错误。You won't be able to
getElementById()
if the document body hasn't even been parsed. In other words, you need to run your code in anwindow.onload
function, or place it at the very bottom of your body.Also, remove the
try/catch
while testing, it will only hide errors.您确定您尝试获取的元素已加载到 DOM 中吗?您说您的脚本在 head 标签中运行(该标签在正文的其余部分加载之前加载)。您的脚本可能在您要搜索的 DOM 元素存在之前运行,因此无法找到它,因此无法添加到该元素。
Are you sure that the element you're trying to get has been loaded into the DOM? You said that your script runs in the head tag (which loads before the rest of the body loads). It's possible that your script is being run before the DOM element you're searching for exists, and therefore it can't find it and therefore it can't add to it.
无法保证 HTML 在 JavaScript 执行时已完成解析。有多种方法可以实现您想要的功能,并且具有不同的性能特征。
您可以将代码放入函数中并将其指定为窗口对象的加载事件处理程序。这样做的缺点是需要等待页面的所有资源(而不仅仅是 HTML)完成加载。这通常会减慢页面加载时间,因为您需要等待缓慢的广告服务器等。
您可以将代码放入函数中并从文档底部调用它。
您可以使用 JavaScript 库(例如 jQuery)在 DOM 加载完成后执行 JavaScript。没有一种可以跨浏览器工作的简单方法,因此最简单的方法是不要重新发明轮子,而只是使用已经成熟的解决方案。
There's no guarantee that the HTML will have finished parsing by the time the JavaScript executes. There are several ways of doing what you want, with different performance characteristics.
You can put your code in a function and assign it as the load event handler for the window object. This has the downside of waiting until all resources for the page have finished loading, not just the HTML. This often slows down page load times, as you need to wait for things like slow ad servers etc.
You can put your code in a function and call it from bottom of the document.
You can use a JavaScript library such as jQuery to execute your JavaScript when the DOM has finished loading. There isn't a simple way of doing this that works cross-browser, so it's simplest not to reinvent the wheel and just to use what is already a mature solution.