語法
js
new Option()
new Option(text)
new Option(text, value)
new Option(text, value, defaultSelected)
new Option(text, value, defaultSelected, selected)
引數
text可選-
一個字串,表示元素的文字內容,即顯示的文字。如果未指定此項,則使用預設值 ""(空字串)。
value可選-
一個字串,表示
HTMLOptionElement的值,即等效的<option>的 value 屬性。如果未指定此項,則使用 text 的值作為 value,例如,在表單提交到伺服器時,此值將是關聯的<select>元素的值。 defaultSelected可選-
一個布林值(
true或false),用於設定selected屬性的值,即當頁面首次載入時,此<option>將是<select>元素中預設選中的值。如果未指定此項,則使用預設值 false。請注意,如果選項未被選中,即使值為 true,也不會將其設定為選中狀態。 selected可選-
一個布林值(
true或false),用於設定選項的選中狀態;預設值為 false(未選中)。如果省略,即使 defaultSelected 引數為 true,選項也不會被選中。
示例
僅新增新選項
js
/* assuming we have the following HTML
<select id='s'>
</select>
*/
const s = document.getElementById("s");
const options = [Four, Five, Six];
options.forEach((element, key) => {
s[key] = new Option(element, key);
});
追加帶有不同引數的選項
html
<select id="s"></select>
js
const s = document.getElementById("s");
const options = ["zero", "one", "two"];
options.forEach((element, key) => {
if (element === "zero") {
s[key] = new Option(element, s.options.length, false, false);
}
if (element === "one") {
s[key] = new Option(element, s.options.length, true, false); // Will add the "selected" attribute
}
if (element === "two") {
s[key] = new Option(element, s.options.length, false, true); // Will actually be selected in the view
}
});
結果
html
<select id="s">
<option value="0">zero</option>
<option value="1" selected>one</option>
<option value="2">two</option>
<!-- User will see two as 'selected' -->
</select>
規範
| 規範 |
|---|
| HTML # dom-option-dev |
瀏覽器相容性
載入中…