【问题标题】:JavaScript loop returning undefinedJavaScript 循环返回未定义
【发布时间】:2013-07-17 06:43:52
【问题描述】:

我正在尝试编写一个函数,该函数将遍历我的“主”div 元素的子节点,并将元素标记名称输出到 hmtl 页面上,每次我尝试编译我的代码时,我最终都会得到未定义.任何人都可以解释为什么?

可能是因为 Console.log 返回 undefined 吗?但如果它不应该我仍然从我的 for 循环中接收某种输出?

function looper() {         //function that will loop through the child nodes of main

    var nodes = document.getElementById('main').childNodes;

    for(i=0; i<nodes.length; i++) {
        console.log(nodes[i]);
    }
}

HTML

 <div id ="main">

 <h1> Jimms web site </h1>

 <nav>
   <a href="index.html">Home page</a> |
   <a href="about.html">About me</a> |
   <a href="contact.html">Contact me</a> 
 </nav> 

     <p> This is a list: </p>
     <div> 
     <ol id = "list">
      <li><a href="mega">hi</a> - </li>
      <li><a href="mario">mario</a> - </li>
      <li><a href="luigi">luigi</a> - </li>
      <li><a href="mash">mash</a> - </li>
      <li><a href="mash">mash</a> - </li></ol>
      </div>
      <p> Thats it </p>



 </div>

  looper();

【问题讨论】:

  • 首先,我建议使用.children 而不是.childNodes
  • 这样做后,我的未定义计数从 21 例变为 10 例。但是,我不明白为什么要这样做,我不明白为什么病例下降了。
  • .children 仅提供元素,而 .childNodes 包含不必要的文本节点。
  • 在循环之前,添加console.log(nodes); 并检查控制台的值。
  • -- [02:57:01.604] ({0:{}, 1:{}, 2:{}, 3:{}, 4:{}, 5:{}, 6 :{}, 7:{}, 8:{}, 9:{}}) 是我在循环前得到的控制台日志

标签: javascript loops undefined


【解决方案1】:

您可能在 DOM 准备好之前调用了 javascript。在结束 body 标记之前调用函数。

Live Demo

function looper() {         //function that will loop through the child nodes of main

    var nodes = document.getElementById('main').childNodes;

    for(i=0; i<nodes.length; i++) {
        document.write(nodes[i]);
    }
}

在body标签之前调用looper,保证DOM元素的可用性。

    <script type="text/javascript" >
        looper();
    </script> 

</body>   

【讨论】:

  • 不包含脚本。在 HTML 中
  • 您需要将 looper 放入脚本标签中,正如我在回答中所展示的那样,请在此处查看演示,jsfiddle.net/M3jaQ
猜你喜欢
  • 1970-01-01
  • 2016-06-19
  • 2019-10-05
  • 2012-11-29
  • 2013-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多