JS对select动态添加options操作[IE&FireFox兼容]

做一个项目,遇到了要动态调整 select 选项的情况,就baidu了一下,发现了一篇与本文同名的帖子.

但是呢,那个帖子里的方法并不兼容.  

附原文:

<select id="ddlResourceType" onchange="getvalue(this)">
</select>

   动态删除select中的所有options:
       document.getElementById("ddlResourceType").options.length=0;

     动态删除select中的某一项option:
       document.getElementById("ddlResourceType").options.remove(indx);
  
//就是这句不兼容了,Firefox是不懂 remove 这个方法的,所以会报错了,当然也移除不了了

    动态添加select中的项option:
       document.getElementById("ddlResourceType").options.add(new Option(text,value));

   上面在IE和FireFox都能测试成功,希望以后你可以用上。
其实用标准的DOM操作也可以,就是document.createElement,appendChild,removeChild之类的。

    取值方面
    function getvalue(obj)
     {
         var m=obj.options[obj.selectedIndex].value
         alert(m);//获取value
         var n=obj.options[obj.selectedIndex].text
         alert(n);//获取文本
     }

后来,发现这篇文章末端的那几句话,觉得可以用dom试试,嗯,果然可行.

var sObj=document.getElementById("ddlResourceType");

sObj.removeChild(sObj.options[indx]);

这样,上面这句就做到兼容了.

其他的代码都没有问题,可以兼容.  

原文地址:https://www.cnblogs.com/footleg/p/1281425.html