innerHTML 产生未定义,但正确的数据可见

发布于 2024-09-04 19:52:52 字数 674 浏览 3 评论 0原文

    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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

中二柚 2024-09-11 19:52:52

Model 最初是一个未初始化的变量,包含 undefined。在循环中,您使用 += 向其附加字符串,因此在第一次迭代中,第一个字符串被“附加”到初始 undefined 值。为此,javascript 将 undefined 转换为字符串并将新字符串附加到其中,这样您最终会得到一个以“undefined”开头的字符串。

如果您使用空字符串初始化 Model ,问题就会消失:

Model = '';

Model starts out as an uninitialized variable, containing undefined. In the loop you append strings to it with +=, so in the first iteration the first string is "appended" to the initial undefined value. To do this javascript converts undefined 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:

Model = '';
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文