萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript Select 下拉選單操作全攻略:增刪改查與跨瀏覽器兼容

Select 下拉選單的動態操作(添加、刪除、修改、查詢選項)是表單開發高頻需求。本文整理原生 JS 與 jQuery 兩套方案,重點解決跨瀏覽器兼容性陷阱。

原生 JavaScript 核心操作

1. 獲取 Select 對象


var select = document.getElementById("mySelect"); // 推薦用 ID
// 或
var select = document.querySelector("#mySelect");

2. 選項增刪改查


// --- 添加選項 ---
// 方式一:Option 構造函數(標準、推薦)
var option = new Option("顯示文本", "value值");
select.add(option); // 標準方法
// select.options.add(option); // 兼容寫法

// 方式二:createElement
var option = document.createElement("option");
option.value = "value值";
option.text = "顯示文本";
select.appendChild(option);

// 指定位置插入
select.insertBefore(option, select.options[1]); // 插入到第 2 個前

// --- 刪除選項 ---
// 刪除指定索引
select.remove(1); // 標準:參數為索引
// select.options[1] = null; // 兼容寫法(原文提到的 IE/FF 通用)

// 刪除所有(保留第一項提示)
for (var i = select.options.length - 1; i > 0; i--) {
    select.remove(i);
}

// --- 修改選項 ---
select.options[0].text = "新文本";
select.options[0].value = "新值";

// --- 查詢/獲取 ---
var selectedIndex = select.selectedIndex;        // 選中索引
var selectedValue = select.value;                // 選中值
var selectedText = select.options[selectedIndex].text; // 選中文本
var selectedOption = select.options[selectedIndex];    // 選中 Option 元素

// 遍歷所有選項
for (var i = 0; i < select.options.length; i++) {
    console.log(select.options[i].value, select.options[i].text);
}

3. 設置選中項


// 方式一:value 匹配(推薦)
select.value = "targetValue";

// 方式二:索引設置
select.selectedIndex = 2;

// 方式三:Option 元素 selected 屬性
select.options[2].selected = true;

跨瀏覽器兼容性關鍵點

操作標準/現代IE 兼容寫法推薦
添加選項select.add(option)select.add(option) / select.options.add(option)select.add(option)
刪除選項select.remove(index)select.options[index] = nullselect.remove(index)
清空選項select.innerHTML = ""while(select.options.length) select.remove(0)select.options.length = 0
獲取選中文本select.selectedOptions[0].textselect.options[select.selectedIndex].textselect.options[select.selectedIndex].text

jQuery 簡化操作


// 獲取值/文本
$("#mySelect").val();                    // 值
$("#mySelect option:selected").text();   // 文本

// 設置選中
$("#mySelect").val("targetValue");       // 通過值
$("#mySelect")[0].selectedIndex = 2;     // 通過索引

// 添加選項
$("#mySelect").append('');
// 或
$("');

// 綁定變化事件
$("#mySelect").on("change", function() {
    console.log($(this).val(), $(this).find("option:selected").text());
});

實戰場景:動態載入城市數據


// 模擬異步獲取數據
function loadCities(provinceId, callback) {
    setTimeout(function() {
        var data = {
            "1": [{id: "1", name: "北京"}, {id: "2", name: "天津"}],
            "2": [{id: "3", name: "上海"}, {id: "4", name: "重慶"}]
        };
        callback(data[provinceId] || []);
    }, 300);
}

// 聯動邏輯
$("#province").on("change", function() {
    var $city = $("#city");
    var provinceId = $(this).val();

    $city.empty().append('').prop("disabled", true);

    if (!provinceId) {
        $city.html('');
        return;
    }

    loadCities(provinceId, function(cities) {
        $city.empty().append('');
        $.each(cities, function(i, city) {
            $city.append($("

性能優化建議

  1. 大量選項:使用 `DocumentFragment` 批量創建,或虛擬滾動組件(如 Select2、Choices.js)
  2. 頻繁操作:緩存 `$select = $("#mySelect")`,避免重複選擇器查詢
  3. 事件委託:動態生成的 select 用 `$(document).on("change", "#dynamic-select", handler)`

無障礙增強




// JS 設置值後觸發 change 事件通知輔助技術
$("#accessible-select").val("bj").trigger("change");

掌握 Select 完整操作 API 與兼容性細節,能讓您在維護舊項目、開發無依賴組件、處理複雜聯動場景時得心應手。

copyright © 萬盛學電腦網 all rights reserved