使用createElement()创建checkbox不能设置name属性

本文探讨了在Internet Explorer 6和7中使用document.createElement()方法动态创建复选框时遇到的问题——无法正确设置复选框的name属性。此问题在Firefox浏览器中不存在,并提供了一种解决方案。
今天在使用document.createElement()动态创建复选框时,发现不能为其name赋值,以下是测试代码:
  1. <html>
  2. <head>
  3. <title>Test</title>
  4. </head>
  5. <body>
  6. <divid="testDiv"></div>
  7. <inputtype="button"onclick="addInput()"value="Test0">
  8. <inputtype="button"onclick="show()"value="Test1">
  9. <scriptlanguage="javascript">
  10. functionaddInput(){
  11. vardiv=document.getElementById("testDiv");
  12. for(varii=0;ii<5;ii++){
  13. varcheck=document.createElement("input");
  14. check.type="checkbox";
  15. check.id="chk_"+ii;
  16. check.name="chkGroup";
  17. div.appendChild(check);
  18. }
  19. alert(div.innerHTML);
  20. }
  21. functionshow(){
  22. alert(document.getElementsByName("chkGroup").length);
  23. }
  24. </script>
  25. </body>
  26. </html>

其中check.name = "chkGroup"这句话并不能起到预期的作用,无论是看生成后的HTML代码还是观察使用document.getElementsByName()获取的数组长度,都会发现这个name设置并没有起作用。当然这种情况只出现在IE6和IE7中,而在FireFox中是没有问题的。
当然解决方法很简单,在创建时,使用document.createElement("<input name='chkGroup'>")。不过还不知道是什么原因?
在Name属性的说明中有这样一句话:

In Internet Explorer 5, the name property cannot be set at run time on anchor objects dynamically created with the createElement method. To create an anchor with a NAME attribute, include the attribute and value when using the createElement method, or use the innerHTML property.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值