动态创建radio、checkbox时需要注意的问题

时间:2022-11-19 19:23:43

1、给radio、checkbox后面添加文字

2、创建默认选中

3、创建完可选

  1. function create(){
  2. var board = document.getElementById("layer1_content1");
  3. var e = createElement("input","cpname");
  4. e.type = "checkbox";
  5. e.id = "chid";
  6. e.value ="123";
  7. board.appendChild(e);
  8. //设置选中
  9. e.setAttribute("checked","checked");
  10. //添加文字
  11. board.appendChild(document.createTextNode("测试"));
  12. }
  13. function createElement(type, name) {
  14. var element = null;
  15. try {
  16. // First try the IE way; if this fails then use the standard way
  17. element = document.createElement('<'+type+' name="'+name+'">');
  18. } catch (e) {
  19. // Probably failed because we’re not running on IE
  20. }
  21. if (!element) {
  22. element = document.createElement(type);
  23. element.name = name;
  24. }
  25. return element;
  26. }
function create(){
var board = document.getElementById("layer1_content1");
var e = createElement("input","cpname");
e.type = "checkbox";
e.id = "chid";
e.value ="123";
board.appendChild(e);
//设置选中
e.setAttribute("checked","checked");
//添加文字
board.appendChild(document.createTextNode("测试"));
} function createElement(type, name) {
var element = null;
try {
// First try the IE way; if this fails then use the standard way
element = document.createElement('<'+type+' name="'+name+'">');
} catch (e) {
// Probably failed because we’re not running on IE
}
if (!element) {
element = document.createElement(type);
element.name = name;
}
return element;
}

注意:1、由于IE的问题,必须使用以上createElement()方法创建name属性,否则在IE中无法选中,其他浏览器不需要这样。

2、在IE浏览中,通过document.createElement("input")来生成的radio和checkbox都无法通过document.getElementsByName()方法来获取