select设置innerHMTL

select控件在标准浏览器下可以直接innerHTML设置内容,IE则不行。

HTML结构:

<form name="form1">
    <select name="select1"></select>
</form>

 

先看直接使用select.innerHTML

var form = document.forms["form1"];
    var select = form["select1"];
    select.innerHTML = '<option value="1">1</option>';

 

运行发现标准浏览器如chrome, firefox运行正常,DOM树为

IE(678)全家都呵呵了:

原因在于IE使用innerHTML给select赋值时会根据/^<\w\d['" ]>&/(尖括号中间的字母、数字,引号,空格)匹配的字符都干掉,无力吐槽。

 

2种解决思路

 

1、使用select的outerHTML或者父级的innerHMTL

var select = document.forms["form1"]["select1"];
select.outerHTML = '<select name="select1"><option value="1">1</option></select>';

 

outerHMTL IE系列和chrome是支持的,新版的FireFox也支持,国内Firefox浏览器份额低的可以忽略不计。如果嫌弃outerHTML,当然可以换innerHTML

document.forms["form1"].innerHTML = '<select name="select1"><option value="1">1</option></select>';

  简单暴力

 

2、使用new Option创建select的options,这是比较推荐的方法。

    var form = document.forms["form1"];
    var select = form["select1"];
    select.options.add(new Option("text", "value")); // 或 select.add(new Option("text", "value"))

  new Option创建一个option对象实例,依次接受text,value两个参数,text为option的文本值,value即为option的value值。

发散思维,几种常见的option操作做个汇总:

    var form = document.forms["form1"];
    var select = form["select1"];
    
    // 增加
    select.options.add(new Option("text1", "value1")); // 或 select.add(new Option("text1", "value1"))
    select.options.add(new Option("text2", "value2")); // 或 select.add(new Option("text2", "value2"))
    
    // 删除选中项,也可指定删除
    var index = select.options.selectedIndex;
    select.options.remove(select.index); // 或 select.remove(select.index)
    
    // 全删
    select.options.length = 0;

    // 改text
    select.options[select.selectedIndex].text = "text3"; 
    // 改value
    select.options[select.selectedIndex].value = "value3";
    // 同时修改text | value
    select.options[select.selectedIndex] = new Option("text3", "value3");
    
    //
    var text = select.options[select.selectedIndex].text;
    var value = select.options[select.selectedIndex].value;

 

 

 

posted @ 2014-04-28 23:27  司马缸  阅读(850)  评论(0编辑  收藏  举报