Checkbox的checked属性问题

来源:百度文库 编辑:神马文学网 时间:2024/04/30 23:39:58

Checkbox的checked属性问题

转自:http://www.cnblogs.com/net205/archive/2008/08/31/1280432.html

 

  前几天开发中用Javascript脚本创建Checkbox时,发现设置checked属性有问题,后来测试得到设置checked属性在IE,Firefox,Opera中存在差异。

 

   我们先来看一下网上搜索到的例子。

  1、Internet Explorer 6 and the checked checkbox

   http://claudio.cicali.org/article/90/ie-6-and-the-checked-checkbox 

   You dinamically create a checkbox and then put its state tochecked. Then, you append your new checkbox to its parent. In firefoxthere’s nothing wrong with that. But Internet Explorer DOES NOT checkthe box. Why? Well, FIRST you have to show the checkbox and THEN checkit.

 

So: 

Html代码
  1. chk = document.createElement('INPUT')  
  2. chk.type='checkbox'  
  3. chk.checked=true  
  4. document.getElementById('container').appendChild(chk)  

 Does not work in IE. You have to rewrite this as:

Html代码
  1. chk = document.createElement('INPUT')  
  2. chk.type='checkbox'  
  3. document.getElementById('container').appendChild(chk)  
  4. chk.checked=true  

 

从这里我们可以看出在IE中,checked属性需要在添加到页面以后设置才有效,而FF,Opera都不存在此现象。

 

  2、firefox和ie下面的初始化checkbox
http://www.cnblogs.com/sxlfybb/archive/2008/03/20/1114242.html

 

   这篇日志得出同样的结果。(申明:firefox下是支持cb.checked=true这样的写法,checked是一个可读写的属性。至少我的环境是正常的。)

 

  3、使用CheckBox的indeterminate属性的问题

   http://blog.csdn.net/yangdengfeng2003/archive/2007/05/05/1597399.aspx 

 

   这篇日志提到了CheckBox的indeterminate属性的问题,注意:CheckBox的indeterminate是一个独立的属性,和CheckBox的checked、status的取值无关,也就是说它只会影响CheckBox的外观显示,我们仍然可以正常的使用脚本读取checked和status的值。

 

   4、DOM & checkbox(checked status)

   http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=842144&SiteID=1

 

        帖子中提到Checkbox在IE6和IE7下的多种情况。(此帖子中的代码本人没有测试过。)

 

   最后看看本人测试结果及结论:

 

Html代码
  1.  1   
  2.  2   
  3.  3    
  4.  4   CheckBox Example  
  5.  5     
  6.  6     
  7.  7     
  8.  8     
  9.  9     
  10. 10    
  11. 11   
  12. 12   
  13. 13 <%  
  14. 14     Response.Buffer = true  
  15. 15     Response.Expires = 0  
  16. 16     Response.ExpiresAbsolute = Now() - 1       
  17. 17     Response.CacheControl = "no-cache"    
  18. 18     Response.AddHeader "Pragma", "No-Cache"   
  19. 19   
  20. 20     For Each e In Request.Form  
  21. 21         Response.Write e & " : " & Request.Form(e) & ""  
  22. 22     Next  
  23. 23   
  24. 24 %>  
  25. 25   
  26. 26       
  27. 27       
  28. 40       
  29. 41   
  30. 42   
  31. 43   
 

 

   结论:
1、当用Javascript脚本创建并添加CheckBox复选框时,对于IE,必须在添加(如:appendChild)后设置checked值才有效,FF、OP都有效,无此现象。
2、defaultChecked直接写到属性里,IE、FF、OP都不支持,当用Javascript脚本设置为true时,都支持(无顺序关系),并在服务器端可以取到值。
3、indeterminate当属性添加时IE、FF、OP都无效,只有当用Javascript脚本设置时,IE才有效,并在服务器端取不到值,只会影响CheckBox的外观显示。
4、当用setAttribute设置checked值时,如果为unchecked状态,对于FF、OP则不需要设置任何值,就算设置为fasle、"false"或""(空字符串),checkbox都为选中状态。

   5、类似document.createElement("");创建元素时,只有IE才有效。


说明:本人测试环境为IE6.0 sp2、Firefox 3.0.1、Opera 9.52,如有其他情况,请各位同仁指出。