JS操做select標籤

主要利用這個來實現省市區三級聯動的html

我利用的是ajax,每一次onchange事件都改變相對應的select中的option,數據全是ajax請求服務器查詢數據庫而來的,效果還能夠,在本地測試的時候速度仍是能夠的,用戶基本體會不到帶來的輕微卡頓,還有種方式是把數據直接寫在本地的js中做爲數組存放起來,可是個人數據已經在數據庫中,因此這種方式被我否認了,可是我認爲這種方式運行速度應該比個人快。ajax

下面是JS操做select的幾種用法,經常使用的我就記錄一下。數據庫

1.動態建立select數組

     function createSelect(){服務器

var mySelect = document.createElement_x("select");
          mySelect.id = "mySelect"; 
          document.body.appendChild(mySelect);
      }app

2.添加選項option測試

     function addOption(){firefox

          //根據id查找對象,
           var obj=document.getElementByIdx_x('mySelect');htm

           //添加一個選項
obj.add(new Option("文本","值"));    //這個只能在IE中有效
         obj.options.add(new Option("text","value")); //這個兼容IE與firefox
     }對象

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);
     }

 

部分轉載自:http://www.cnblogs.com/dchly/archive/2012/11/07/2759250.html

相關文章
相關標籤/搜索