<select id="demo" name="demo">
<option value="1">選項 1</option>
<option value="2" selected>選項 2</option>
<option value="3">選項 3</option>
</select>
// 單選
$('#demo').val(); // 值: "2"
$('#demo option:selected').text(); // 文本: "選項 2"
$('#demo').prop('selectedIndex'); // 索引: 1
// 多選
$('#multi').val(); // 陣列: ["1", "3"]
$('#multi option:selected').map((i,el)=>el.text).get(); // 文本陣列
// 由值
$('#demo').val('3'); // 選中 value="3"
// 由索引
$('#demo').prop('selectedIndex', 2); // 選中第 3 項
// 由文本(需遍歷)
$('#demo option').filter(function() {
return $(this).text() === '選項 3';
}).prop('selected', true);
// 單個添加(推薦 new Option,無 XSS、效能高)
$('#demo').append(new Option('選項 4', '4'));
// 批量添加
const data = [{id:4, name:'四'},{id:5, name:'五'}];
const options = data.map(d => new Option(d.name, d.id));
$('#demo').append(options);
// 指定位置插入
$('#demo option:eq(1)').after(new Option('新二', '2.5')); // 第 2 項後
$('#demo option:first').before(new Option('新首', '0')); // 首項前
// 刪除指定值
$('#demo option[value="2"]').remove();
// 刪除指定索引
$('#demo option:eq(1)').remove(); // 第 2 項
// 刪除選中項
$('#demo option:selected').remove();
// 保留首項(如「請選擇」),刪除其餘
$('#demo option:not(:first)').remove();
// 清空所有
$('#demo').empty();
// 或保留首項
$('#demo option:not(:first)').remove();
$('#demo').val(''); // 重置選中狀態
// jQuery each
$('#demo option').each(function(i, el) {
console.log(i, el.value, el.text);
});
// 原生 forEach(現代瀏覽器)
[...document.getElementById('demo').options].forEach((opt, i) =>
console.log(i, opt.value, opt.text)
);
| 類型 | 獲取值 | 設置值 | 備註 |
|---|---|---|---|
| 文本框/域 | $('#txt').val() | $('#txt').val('新值') | |
| 單選框 | $('input[name=sex]:checked').val() | $('input[name=sex][value=1]').prop('checked',true) | 同 name 分組 |
| 復選框 | $('#chk').prop('checked') / $('#chk').is(':checked') | $('#chk').prop('checked', true/false) | 布爾屬性用 prop |
| 下拉框 | $('#sel').val() | $('#sel').val('值') | 多選返回陣列 |
const cityData = {
beijing: ['朝陽區', '海淀區', '東城區'],
shanghai: ['浦東新區', '黃浦區', '徐匯區']
};
$('#province').on('change', function() {
const province = $(this).val();
const $city = $('#city').empty().append('');
if (province && cityData[province]) {
cityData[province].forEach(city => {
$city.append(new Option(city, city));
});
}
});
const select = document.getElementById('demo');
// 獲取值
select.value;
// 設置值
select.value = '3';
// 獲取選中文本
select.options[select.selectedIndex].text;
// 添加選項
select.append(new Option('文本', '值'));
// 刪除選項
select.remove(index); // 或 select.options[index] = null
// 清空
select.options.length = 0;
select.innerHTML = ''; // 重置含提示項
優勢:零依賴、效能極致、TypeScript 類型友好、無版本鎖定。
jQuery Select 操作核心 API 只有幾個:
.val() —— 獲取/設置值(單選字串、多選陣列).prop('selectedIndex') —— 索引操作option:selected —— 選中項選擇器new Option(text, value) —— 創建選項(最佳實踐).remove() / .empty() —— 刪除/清空理解值 vs 文本、索引 vs 值、單選 vs 多選的區別,配合原生 HTMLSelectElement API,即可應對所有下拉框交互場景。