HTML 示例
<select id="city" name="city">
<option value="" selected>請選擇城市</option>
<option value="bj">北京</option>
<option value="sh">上海</option>
<option value="gz">廣州</option>
<option value="sz">深圳</option>
</select>
三種核心值獲取方式
| 需求 | 代碼 | 結果示例 | 說明 |
| 選中項的顯示文本 | select.options[select.selectedIndex].text | "上海" | 用戶可見的標籤文字 |
| 選中項的 value 值 | select.value 或 select.options[select.selectedIndex].value | "sh" | 表單提交攜帶的值,**推薦用 `.value`** |
| 選中項的索引 | select.selectedIndex | 1 (0-based) | 未選擇時為 -1 |
完整交互示例
<select id="city" onchange="showInfo(this)">...</select>
<div id="output"></div>
<script>
function showInfo(select) {
const idx = select.selectedIndex;
const val = select.value;
const txt = idx >= 0 ? select.options[idx].text : '無';
document.getElementById('output').innerHTML =
`索引: ${idx} <br> Value: ${val} <br> Text: ${txt}`;
}
</script>
多選下拉框 (multiple) 特殊處理
<select id="multi" multiple>
<option value="a">A</option>
<option value="b" selected>B</option>
<option value="c" selected>C</option>
</select>
<script>
const sel = document.getElementById('multi');
// 獲取所有選中項
const selected = [...sel.selectedOptions].map(opt => ({
index: opt.index,
value: opt.value,
text: opt.text
}));
console.log(selected); // [{index:1,value:'b',text:'B'},{index:2,value:'c',text:'C'}]
// 兼容舊瀏覽器
const arr = [];
for (let i=0; i
動態操作 Select
const sel = document.getElementById('city');
// 1. 添加選項
sel.add(new Option('杭州', 'hz')); // 追加到末尾
sel.add(new Option('置頂', 'top'), sel.options[0]); // 插入到索引 0 前
// 2. 刪除選項
sel.remove(0); // 刪除索引 0
// 或
sel.options[sel.options.length-1] = null; // 刪除最後一個
// 3. 程式化選中
sel.value = 'gz'; // 通過 value 選中(最簡潔)
sel.selectedIndex = 2; // 通過索引選中
jQuery 簡寫(若已引入)
$('#city').val(); // 獲取 value
$('#city').find('option:selected').text(); // 獲取文本
$('#city').prop('selectedIndex'); // 獲取索引
$('#city').val('sh'); // 設置 value 選中
常見坑點
- 未選擇時 `selectedIndex === -1`,直接訪問 `options[-1]` 會報錯,**先判斷索引**。
- `select.value` 返回空字符串可能意味著:未選擇、或選中項 `value=""`,**配合 `selectedIndex` 區分**。
- 動態修改 options 後,`selectedIndex` 可能變化,及時同步 UI 狀態。