动态创建radio、checkbox时需要注意的问题
1、给radio、checkbox后面添加文字
2、创建默认选中
3、创建完可选
- 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;
- }
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()方法来获取