这个为什么只输出了一个hobby1呢?大佬们求看

来源:9-5 getAttribute()方法

BurlyLife

2018-06-06 22:16

<!DOCTYPE HTML>

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

        <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 name="get" type="button" value="获取hobby的id属性值" onclick = "getid();">

        </form>

        <script type="text/javascript">

function getid(){

var con=document.getElementsByName("hobby");

var i=0;

while(i<con.length){

    var text=con[i].getAttribute("id");

document.write(text+"<br>");

i++;

}

}

        </script>

    </body>

</html>


写回答 关注

3回答

  • 那人那人
    2018-06-13 17:10:00

    循环里是可以写document.write()的!!!可能是因为onclick 点击事件 点击一下事件发生后,做不了循环;

    BurlyL...

    谢谢,我待会儿试一下

    2018-06-13 17:14:22

    共 1 条回复 >

  • BurlyLife
    2018-06-07 16:28:39

    我就是想问为什么这里不能输出,循环里面可以写document.write()函数吧?

  • 阳火锅
    2018-06-07 12:00:01

    循环里面不能写document.write()这个函数,不信你可以把document.write()换成alert()试一下。。然后text变量要先定义成var text=“” 然后用   text += con[i].getAttribute("id");

    阳火锅 回复BurlyL...

    应该是id的问题。。

    2018-06-07 17:10:06

    共 2 条回复 >

JavaScript进阶篇

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

467374 学习 · 21877 问题

查看课程

相似问题