当前位置: 代码迷 >> Web前端 >> select动态平添options操作
  详细解决方案

select动态平添options操作

热度:150   发布时间:2012-11-25 11:44:31.0
select动态添加options操作
copy下来的 哈哈:
  1. select?id="ddlResourceType"?onchange="getvalue(this)"?

动态删除select中的所有options:

  1. document.getElementById("ddlResourceType").options.length=0;??

动态删除select中的某一项option:

  1. document.getElementById("ddlResourceType").options.remove(indx);? ?
  2. //就是这句兼容性不好,Firefox是不懂?remove?这个方法的,所以会报错了,当然也移除不了了?

动态添加select中的项option:

  1. document.getElementById("ddlResourceType").options.add(new?Option(text,value));?

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

取值方面

  1. function?getvalue(obj) ?
  2. { ?
  3. var?m=obj.options[obj.selectedIndex].value ?
  4. alert(m);//获取value ?
  5. var?n=obj.options[obj.selectedIndex].text ?
  6. alert(n);//获取文本 ?
  7. }?

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

  1. var?sObj=document.getElementById("ddlResourceType"); ?
  2. sObj.removeChild(sObj.options[indx]);?

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

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

  相关解决方案