Option() - Web APIs 编辑

The Option() constructor creates a new HTMLOptionElement.

Syntax

var optionElementReference = new Option(text, value, defaultSelected, selected);

Parameters

text Optional
A DOMString representing the content of the element, i.e. the displayed text. If this is not specified, a default value of "" (empty string) is used.
value Optional
A DOMString representing the value of the HTMLOptionElement, i.e. the value attribute of the equivalent <option>. If this is not specified, the value of text is used as the value, e.g. for the associated <select> element's value when the form is submitted to the server.
defaultSelected Optional
A Boolean that sets the selected attribute value, i.e. so that this <option> will be the default value selected in the <select> element when the page is first loaded. If this is not specified, a default value of false is used. Note that a value of true does not set the option to selected if it is not already selected.
selected Optional
A Boolean that sets the option's selected state; the default is false (not selected). If omitted, even if the defaultSelected argument is true, the option is not selected.

Examples

Just add new options

 /* assuming we have the following HTML
<select id='s'>

</select>
*/

var s = document.getElementById('s');
var options = [Four, Five, Six];

options.forEach(function(element,key) {
    s[key] = new Option(element,key);
});

Append options with different parameters

/* assuming we have the following HTML
<select id="s">
    <option>First</option>
    <option>Second</option>
    <option>Third</option>
</select>
*/

var s = document.getElementById('s');
var options = [ 'zero', 'one', 'two' ];

options.forEach(function(element, key) {
  if (element == 'zero') {
    s[s.options.length] = new Option(element, s.options.length, false, false);
  }
  if (element == 'one') {
    s[s.options.length] = new Option(element, s.options.length, true, false); // Will add the "selected" attribute
  }
  if (element == 'two') {
    s[s.options.length] = new Option(element, s.options.length, false, true); // Just will be selected in "view"
  }
});

/* Result
<select id="s">
  <option value="0">zero</option>
  <option value="1" selected="">one</option>
  <option value="2">two</option> // User will see this as 'selected'
</select>
*/

Specifications

Specification
HTML Living Standard
The definition of 'Option()' in that specification.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:106 次

字数:4878

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文