萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> 網頁設計

JavaScript 動態操作 Select 下拉選單完全指南:創建、增刪改查 8 大核心操作

Select 元素動態操作全攻略

<select> 是表單中最常見的下拉選擇控件。原生 JS 提供了完整的 API 進行動態操作,無需依賴 jQuery。以下是 8 大核心操作的標準寫法與兼容性說明。

1. 動態創建 Select

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

2. 添加選項

function addOption() {
  var select = document.getElementById('mySelect');
  
  // 僅 IE 支援
  select.add(new Option("文本", "值"));
  
  // 標準寫法,兼容所有現代瀏覽器(含 IE)
  select.options.add(new Option("text", "value"));
  
  // 追加到末尾(推薦)
  select.add(new Option("text", "value"), null);
}

3. 刪除所有選項

function removeAll() {
  var select = document.getElementById('mySelect');
  select.options.length = 0;  // 最簡潔高效
  // 或循環移除:while(select.options.length) select.remove(0);
}

4. 刪除指定選項

function removeOne(index) {
  var select = document.getElementById('mySelect');
  // index 可傳入 selectedIndex 或具體序號
  select.remove(index);  // 標準 DOM 方法,比 options.remove() 更通用
}

5. 獲取選中項的值

function getSelectedValue() {
  var select = document.getElementById('mySelect');
  return select.value;  // 直接取 value,最簡單
  // 兼容寫法:select.options[select.selectedIndex].value
}

6. 獲取選中項的文本

function getSelectedText() {
  var select = document.getElementById('mySelect');
  var idx = select.selectedIndex;
  return idx !== -1 ? select.options[idx].text : '';
}

7. 修改選項

function updateOption(index, newText, newValue) {
  var select = document.getElementById('mySelect');
  if (index >= 0 && index < select.options.length) {
    select.options[index] = new Option(newText, newValue);
  }
}

8. 刪除整個 Select

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

完整可運行實例

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Select 動態操作演示</title>
</head>
<body>
  <button onclick="createSelect()">創建 Select</button>
  <button onclick="addOption()">添加選項</button>
  <button onclick="removeOne()">刪除選中</button>
  <button onclick="removeAll()">清空所有</button>
  <button onclick="alert(getSelectedValue())">取值</button>
  <button onclick="alert(getSelectedText())">取文本</button>
  <button onclick="removeSelect()">銷毀 Select</button>
  <hr/>
  <div id="container"></div>

  <script>
  function $(id) { return document.getElementById(id); }
  
  function createSelect() {
    var sel = document.createElement("select");
    sel.id = "mySelect";
    sel.size = 5;  // 顯示多行便於觀察
    $("container").appendChild(sel);
  }
  
  function addOption() {
    var sel = $("mySelect");
    if (!sel) return alert("請先創建 Select");
    var text = prompt("輸入顯示文本:", "選項" + (sel.options.length + 1));
    var value = prompt("輸入提交值:", "val" + (sel.options.length + 1));
    if (text !== null && value !== null) {
      sel.add(new Option(text, value), null);
    }
  }
  
  function removeOne() {
    var sel = $("mySelect");
    if (!sel) return;
    var idx = sel.selectedIndex;
    if (idx !== -1) sel.remove(idx);
    else alert("請先選中一項");
  }
  
  function removeAll() {
    var sel = $("mySelect");
    if (sel) sel.options.length = 0;
  }
  
  function getSelectedValue() {
    var sel = $("mySelect");
    return sel ? sel.value : "Select 不存在";
  }
  
  function getSelectedText() {
    var sel = $("mySelect");
    if (!sel) return "Select 不存在";
    var idx = sel.selectedIndex;
    return idx !== -1 ? sel.options[idx].text : "未選中";
  }
  
  function removeSelect() {
    var sel = $("mySelect");
    if (sel) sel.parentNode.removeChild(sel);
  }
  </script>
</body>
</html>

進階技巧:批量數據綁定

function bindData(selectId, dataArray, textField, valueField, defaultValue) {
  var select = document.getElementById(selectId);
  select.options.length = 0;  // 清空
  
  var fragment = document.createDocumentFragment();  // 文檔片段優化性能
  dataArray.forEach(function(item) {
    var opt = new Option(item[textField], item[valueField]);
    fragment.appendChild(opt);
  });
  select.appendChild(fragment);
  
  if (defaultValue !== undefined) select.value = defaultValue;
}

// 使用示例
var cities = [
  {name: "北京", code: "BJ"},
  {name: "上海", code: "SH"},
  {name: "廣州", code: "GZ"}
];
bindData("citySelect", cities, "name", "code", "SH");

性能提示:大量選項(>1000)時,使用 DocumentFragment 批量追加,避免頻繁觸發重排重繪。現代框架(Vue/React)建議使用虛擬滾動或搜索型下拉組件替代原生 Select。

copyright © 萬盛學電腦網 all rights reserved