Select 下拉選單的動態操作(添加、刪除、修改、查詢選項)是表單開發高頻需求。本文整理原生 JS 與 jQuery 兩套方案,重點解決跨瀏覽器兼容性陷阱。
var select = document.getElementById("mySelect"); // 推薦用 ID
// 或
var select = document.querySelector("#mySelect");
// --- 添加選項 ---
// 方式一: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);
}
// 方式一: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] = null | select.remove(index) |
| 清空選項 | select.innerHTML = "" | while(select.options.length) select.remove(0) | select.options.length = 0 |
| 獲取選中文本 | select.selectedOptions[0].text | select.options[select.selectedIndex].text | select.options[select.selectedIndex].text |
// 獲取值/文本
$("#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($("
// JS 設置值後觸發 change 事件通知輔助技術
$("#accessible-select").val("bj").trigger("change");
掌握 Select 完整操作 API 與兼容性細節,能讓您在維護舊項目、開發無依賴組件、處理複雜聯動場景時得心應手。