为什么for循环在函数里不起作用?

来源:9-4 区别getElementByID,getElementsByName,getElementsByTagName

青灯行

2016-11-03 10:36

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
        <title>无标题文档</title>
    </head>
    <body>
        <form>
          请选择你爱好:<br>
          <input type="checkbox" name="hobby" id="hobby1">  音乐
          <input type="checkbox" name="hobby" id="hobby2">  登山
          <input type="checkbox" name="hobby" id="hobby3">  游泳
          <input type="checkbox" name="hobby" id="hobby4">  阅读
          <input type="checkbox" name="hobby" id="hobby5">  打球
          <input type="checkbox" name="hobby" id="hobby6">  跑步 <br>
          <input type="button" value = "全选" onclick = "checkall();">
          <input type="button" value = "全不选" onclick = "clearall();">
          <p>请输入您要选择爱好的序号,序号为1-6:</p>
          <input id="wb" name="wb" type="text" >
          <input name="ok" type="button" value="确定" onclick = "checkone();">
        </form>
        <script type="text/javascript">
        function checkall(){
           var hobby = document.getElementsByTagName("input");
             for(var i=0;i<hobby.length;i++){
               document.write(hobby[i].type+"<br/>");
             }
        }
        </script>
    </body>
</html>

点击全选checkall()后,只输出一个checkbox。我把for循环放到函数外,就会输出所有的type?

写回答 关注

2回答

  • stone310
    2016-11-12 00:04:17
    已采纳

    因为如果不是自动运行,文档流结束,当点击时,document.write会清除当前页面所有内容,然后for循环中第一次能获取input,输出document,第二次for循环页面已经一篇空白除了刚才输出的内容,因此获取不到input,自然无法继续循环输出

    青灯行

    非常感谢!

    2016-11-14 10:48:06

    共 1 条回复 >

  • 慕粉3233872
    2016-11-03 11:11:28

    应该是hobby[i].nodeType

    还有这里用getElementsByName("hobby")比较好,这样就能获取所有的复选框了

    青灯行 回复慕粉3233...

    一次。

    2016-11-03 19:15:24

    共 5 条回复 >

JavaScript进阶篇

本课程从如何插入JS代码开始,带您进入网页动态交互世界

467395 学习 · 21877 问题

查看课程

相似问题