萬盛學電腦網

 萬盛學電腦網 >> 腳本專題 >> javascript >> JS操作select下拉框動態變動

JS操作select下拉框動態變動

 1.動態創建select

    function createSelect(){

        var mySelect = document.createElement_x("select");

        mySelect.id = "mySelect";  

        document.body.appendChild(mySelect);

    }

2.添加選項option

   function addOption(){

        //根據id查找對象,

         var obj=document.getElementByIdx_x('mySelect');

         //添加一個選項

         obj.add(new    Option("文本","值"));   

   }

3.刪除所有選項option

   function removeAll(){

         var obj=document.getElementByIdx_x('mySelect');

  

         obj.options.length=0;  

   }

4.刪除一個選項option

function removeOne(){

         var obj=document.getElementByIdx_x('mySelect');

         //index,要刪除選項的序號,這裡取當前選中選項的序號

         var index=obj.selectedIndex;

         obj.options.remove(index);  

   }

5.獲得選項option的值

var obj=document.getElementByIdx_x('mySelect');

var index=obj.selectedIndex; //序號,取當前選中選項的序號

var val = obj.options[index].value;

6.獲得選項option的文本

var obj=document.getElementByIdx_x('mySelect');

var index=obj.selectedIndex; //序號,取當前選中選項的序號

var val = obj.options[index].text;

7.修改選項option

var obj=document.getElementByIdx_x('mySelect');

var index=obj.selectedIndex; //序號,取當前選中選項的序號

var val = obj.options[index]=new Option("新文本","新值");

8.刪除select

    function removeSelect(){

          var mySelect = document.getElementByIdx_x("mySelect");

         mySelect.parentNode.removeChild(mySelect);

   }

copyright © 萬盛學電腦網 all rights reserved