select 元素可創建單選或多選菜單,能夠佔據很小的區域,卻包含很多的內容,在政府網站中使用率很高,今天就簡單談談select這個元素。
1.基本屬性
通常來說,我們用select元素來創建下拉列表,用option元素來定義列表中待選擇的選項。一般來說,下來列表的第一個待選項爲默認選項。
默認選中的方法,只需要在option元素添加 "selected = 'selected' " 即可:
<select>
<option>值1</option>
<option selected = 'selected'>值2</option>
<option>值3</option>
</select>
2.動態創建select
var select = document.createElement('select');
select.id = 'mySel';
body.appendChild(select);
3.動態創建option
var mySel = document.getElementById('mySel');
mySel.add(new Option(text,value));
add() 方法用於向 <select> 添加一個 <option> 元素,add(option,before)。
參數 | 描述 |
---|---|
option | 要添加選項元素。必需是 option 或 optgroup元素 |
before | 在選項數組的該元素之前增加新的元素。如果該參數是null,元素添加到選項數組的末尾。 |
4.刪除option
//全部刪除option
mySel.options.length = 0;
//刪除指定索引的option
mySel.options.remove(i); //i爲任意索引值
5.獲取選中的選項
//當前選中的選項的索引
var index = mySel.selectedIndex;
//獲取選中的文本
mySel.options[index].text;
//獲取選中選項的value值
mySel.options[index].value;
好了,讀者可根據select的操作方法,可以嘗試做省級聯動。