日期:2014-05-16  浏览次数:20509 次

动态创建selectjs 操作select和option

转自:http://blog.csdn.net/a313976010/article/details/6728646

?

1.动态创建select

[javascript] view plaincopyprint?
  1. function createSelect(){
  2. var mySelect = document.createElement("select");
  3. mySelect.id = "mySelect";
  4. document.body.appendChild(mySelect);
  5. }
function createSelect(){
          var mySelect = document.createElement("select");
          mySelect.id = "mySelect"; 
          document.body.appendChild(mySelect);
      }

2.添加选项option

[javascript] view plaincopyprint?
  1. function addOption(){
  2. //根据id查找对象,
  3. var obj=document.getElementById('mySelect');
  4. //添加一个选项
  5. obj.add(new Option("文本","值")); //这个只能在IE中有效
  6. obj.options.add(new Option("text","value")); //这个兼容IE与firefox
  7. }
 function addOption(){

          //根据id查找对象,
           var obj=document.getElementById('mySelect');

           //添加一个选项
           obj.add(new Option("文本","值"));    //这个只能在IE中有效
           obj.options.add(new Option("text","value")); //这个兼容IE与firefox
     }

3.删除所有选项option

[javascript] view plaincopyprint?
  1. function removeAll(){
  2. var obj=document.getElementById('mySelect');
  3. obj.options.length=0;
  4. }
  function removeAll(){
           var obj=document.getElementById('mySelect');
           obj.options.length=0;

     }

4.删除一个选项option

[javascript] view plaincopyprint?
  1. function removeOne(){
  2. var obj=document.getElementById('mySelect');
  3. //index,要删除选项的序号,这里取当前选中选项的序号
  4. var index=obj.selectedIndex;
  5. obj.options.remove(index);
  6. }
function removeOne(){
           var obj=document.getElementById('mySelect');

           //index,要删除选项的序号,这里取当前