Latest web development tutorials

HTML DOM Option index 屬性

Option 對象參考手冊 Option對象

定義和用法

index 屬性可返回下拉列表中選項的索引位置。

The index starts at 0.

語法

設置index 屬性:

optionObject.index=integer

返回index 屬性:

optionObject.index


瀏覽器支持

Internet ExplorerFirefoxOperaGoogle ChromeSafari

所有主要瀏覽器都支持index 屬性


實例

實例

本例可返回下拉列表中所選的選項的索引位置:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>本教程(w3big.com)</title>
<script>
function displayResult(){
var x=document.getElementById("mySelect").selectedIndex;
var y=document.getElementById("mySelect").options;
alert("索引: " + y[x].index + " is " + y[x].text);
}
</script>
</head>
<body>

<form>
選擇你最喜歡的水果:
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
</form>
<button type="button" onclick="displayResult()">顯示索引</button>

</body>
</html>

嘗試一下»


Option 對象參考手冊 Option對象