DIV CSS 佈局教程網

JS 動態操作 select 下拉框:創建、增刪、取值全整理
編輯:關於JavaScript     

下拉框的動態操作可以歸納為「建、增、刪、取、改」五類。下面按場景把常用寫法整理在一起,備查很方便。

1. 動態創建 select

function createSelect() {
    var mySelect = document.createElement("select");
    mySelect.id = "mySelect";
    document.body.appendChild(mySelect);
}

2. 添加選項 option

function addOption() {
    var obj = document.getElementById("mySelect");
    obj.add(new Option("文本", "值"));   // 第一個參數是顯示文字,第二個是 value
}

3. 清空所有選項

function removeAll() {
    var obj = document.getElementById("mySelect");
    obj.options.length = 0;
}

4. 刪除單個選項

function removeOne() {
    var obj = document.getElementById("mySelect");
    var index = obj.selectedIndex;   // 當前選中項的序號
    obj.options.remove(index);
}

5. 獲取選項的值與文本

var obj = document.getElementById("mySelect");
var index = obj.selectedIndex;

var val  = obj.options[index].value;   // 值
var text = obj.options[index].text;    // 顯示文本

6. 修改選項

var obj = document.getElementById("mySelect");
var index = obj.selectedIndex;
obj.options[index] = new Option("新文本", "新值");

7. 刪除整個 select

function removeSelect() {
    var mySelect = document.getElementById("mySelect");
    mySelect.parentNode.removeChild(mySelect);
}

幾點實用補充

  • 插入到指定位置時,可以用中鍵的 add(new Option(...), index),或直接操作 insertBefore。
  • 取多選的值時,需要遍歷 options 判斷每一項的 selected,把選中的 value 收集成數組。
  • 清空後記得重置 selectedIndex,某些舊瀏覽器殘留的選中狀態會導致取值異常。
  • 如果數據來源是接口,建議先清空再批量 add,避免逐條渲染帶來的閃爍。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved