HTMLOptionElement:Option() 构造函数

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

Option() 构造函数创建一个新的 HTMLOptionElement

语法

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 可选

一个布尔值(truefalse),用于设置 selected 属性的值,即当页面首次加载时,此 <option> 将是 <select> 元素中默认选中的值。如果未指定此项,则使用默认值 false。请注意,如果选项未被选中,即使值为 true,也不会将其设置为选中状态。

selected 可选

一个布尔值(truefalse),用于设置选项的选中状态;默认值为 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

浏览器兼容性