innerHTML 产生未定义,但正确的数据可见
var Model,node;
document.getElementById('sedans').innerHTML='';
var thismodelabbr,prevmodelabbr;
for(var j=0; j<xmlDoc.getElementsByTagName('data').length; j++){
node = xmlDoc.getElementsByTagName('data')[j];
thismodelabbr=node.getAttribute('model');
if(prevmodelabbr!=thismodelabbr){
Model+='<a href="">'+ node.getAttribute('model')+'</a>';
}
prevmodelabbr=thismodelabbr;
document.getElementById('sedans').innerHTML=Model;
}
上面的 javascript 代码片段可以根据需要正常工作,但是在条目显示在其各自的页面中之前,我收到了“未定义”响应。我假设它与 .innerHTML 调用有关。任何见解将不胜感激。
var Model,node;
document.getElementById('sedans').innerHTML='';
var thismodelabbr,prevmodelabbr;
for(var j=0; j<xmlDoc.getElementsByTagName('data').length; j++){
node = xmlDoc.getElementsByTagName('data')[j];
thismodelabbr=node.getAttribute('model');
if(prevmodelabbr!=thismodelabbr){
Model+='<a href="">'+ node.getAttribute('model')+'</a>';
}
prevmodelabbr=thismodelabbr;
document.getElementById('sedans').innerHTML=Model;
}
The above javascript snippet is working correctly and as needed, but I'm getting an "Undefined" response before the entry is displayed within its respective page. I'm assuming it has to do with the .innerHTML call. Any insight would be deeply appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Model
最初是一个未初始化的变量,包含undefined
。在循环中,您使用+=
向其附加字符串,因此在第一次迭代中,第一个字符串被“附加”到初始undefined
值。为此,javascript 将undefined
转换为字符串并将新字符串附加到其中,这样您最终会得到一个以“undefined”开头的字符串。如果您使用空字符串初始化
Model
,问题就会消失:Model
starts out as an uninitialized variable, containingundefined
. In the loop you append strings to it with+=
, so in the first iteration the first string is "appended" to the initialundefined
value. To do this javascript convertsundefined
to a string and appends the new string to it, so that you end up with a string starting with "undefined".If you initialize
Model
with an empty string the issue should go away: