操作下拉列表(select)時,經常需要取得當前選中選項的顯示文本(text)與對應值(value)。核心思路是透過 selectedIndex 定位選中項,再讀取該 option 的 text 與 value 屬性。
代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
<script type="text/javascript">
function selChange(){
var sel=document.getElementById('sel');
alert(sel.options[sel.selectedIndex].text);
alert(sel.options[sel.selectedIndex].value);
}
</script>
</head>
<body>
<select id="sel" onchange="selChange()" >
<option value="zhangsan">張三</option>
<option value="lisi" >李四</option>
<option value="wangwu" >王五</option>
</select>
</body>
</html>
關鍵點:sel.options[sel.selectedIndex] 拿到當前選中的 option 對象,接著 .text 得到頁面上顯示的文字(如「張三」),.value 得到 value 屬性值(如 zhangsan)。把這段邏輯綁定到 select 的 onchange 事件上,用戶每次切換選項時都能即時獲取對應數據。