日期:2014-05-16  浏览次数:20348 次

js---使用JS向页面动态添加radio
开发过程中,需要使用JS向页面动态添加radio,实现时通过document.createElement()方法来实现,刚开始的代码如下:
1. var _radio = document.createElement("input"); 
2. _radio.type = "radio"; 
3. _radio.name = "_radio"; 
4. document.body.appendChild(_radio); 
5. _radio = document.createElement("input"); 
6. _radio.type = "radio"; 
7. _radio.name = "_radio"; 
8. document.body.appendChild(_radio); 
结果在IE浏览器上生成的raido无法选中,而使用firefox浏览器却可以选中。后来试了下面的代码:
1. var _radio = document.createElement("<input type='radio' name='_radio'>"); 
2. document.body.appendChild(_radio); 
3. _radio = document.createElement("<input type='radio' name='_radio'>"); 
4. document.body.appendChild(_radio); 
结果在IE上生成的radio可以选中了,但firefox浏览器中却无效。为此,对于不同的浏览器,需要使用不同的方式来生成radio,这个可以通过判断document是否具有uniqueID属性实现,因为uniqueID是IE特有的属性,为此可以通过下面代码来做到浏览器的兼容性:
# if(document.uniqueID) { 
#     //IE浏览器分支 
#     var _radio = document.createElement("<input type='radio' name='_radio'>"); 
#     document.body.appendChild(_radio); 
#     _radio = document.createElement("<input type='radio' name='_radio'>"); 
#     document.body.appendChild(_radio); 
# } else { 
#     //非IE浏览器分支 
#     var _radio = document.createElement("input"); 
#     _radio.type = "radio"; 
#     _radio.name = "_radio"; 
#     document.body.appendChild(_radio); 
#     _radio = document.createElement("input"); 
#     _radio.type = "radio"; 
#     _radio.name = "_radio"; 
#     document.body.appendChild(_radio); 
# }
此外,在IE浏览中,通过document.createElement("input")来生成的radio和checkbox都无法通过document.getElementsByName()方法来获取。