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

 

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

2、创建默认选中

3、创建完可选

Js代码 复制代码 收藏代码
  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.     
  14.    function createElement(type, name) {    
  15.        var element = null;    
  16.        try {    
  17.           // First try the IE way; if this fails then use the standard way    
  18.           element = document.createElement('<'+type+' name="'+name+'">');    
  19.        } catch (e) {    
  20.           // Probably failed because we’re not running on IE    
  21.        }    
  22.        if (!element) {    
  23.           element = document.createElement(type);    
  24.           element.name = name;    
  25.        }    
  26.        return element;    
  27.     } 
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()方法来获取

posted @ 2014-12-24 10:17  hannover  阅读(1835)  评论(0编辑  收藏  举报