JS selectedIndex

例如,在HTML中,第1個選單如下:

<select name="pulldown_1" size=1> <option>probiscus
<option>spider
<option>lemur
<option>chimp
<option>gorilla
<option>orangutan
</select>
注意這個選單的名稱是pulldown_1,但各個選項沒有名稱。 所以要調用其中的各個選項則有點困難。
幸好數組可以幫助我們調用其中的選項。如果你想改變該下 列選單中的第2個選項,你可以這樣做:


window.document.form_1.pulldown_1.
options[1].text = 'new_text';

這是因爲選單的元素有一個選項屬性,而該屬性是選單所 有選項的集合而成的數組。點擊change the select然後從下拉選單從下列選單中查看其選項是否已經被改變。現在 第2個選項應該是*thau*。
除了選項屬性,選單還有一項屬性叫做selectedIndex。大 筆一個選項被選擇後,selectedIndex屬性將變成被選項的 數組索引號(序列號)。選擇第2個列表選單中的一個選項, 然後檢查索引號。記住數組中的第1個選項的索引號是0。

<a href="#" onClick="alert(
'index is: '+ window.document.
form_1.list_1.selectedIndex);
return false;">check the index.
</a>
表單的名稱是form_1,列表選單的名稱是list_1。
selectedIndex屬性值爲
window.document.form_1.list_1.
selectedIndex。
你還可 以將selectedIndex設置如下:
window.document.form_1.list_1.
selectedIndex = 1;


並高亮度顯示第2個選項。
一旦你得到被選項的索引號,你就可以發現其內容:

var the_select =
window.document.form_1.list_1;

var the_index =
the_select.selectedIndex;

var the_selected =
the_select.
options[the_index].text;



selectedIndex屬性很有用,但如果有多個選項同時被選中,會如何呢?有關這方面的內容請閱讀multiple selects。
選單元素的處理器爲onChange

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章