使用元素的.options属性,可以动态填充选项和optgroup的选择框?
简化,这是我现在正在做的事情(想象一下循环是动态的,必须通过脚本进行):
var demo = document.getElementById("d").children[0];
for (var i = 1; i <= 5; i++)
{
// this will in this case auto-select and default-select the third option
demo.options[demo.options.length] = new Option("Value: " + i, i, i == 3, i == 3);
}
<div id="d">
<select></select>
</div>
我想实现这样的DOM结构:
<div id="d">
<select>
<optgroup label='Something'>
<option ...
<option ...
</optgroup>
<optgroup label='Something else'>
<option ...
<option ...
<option ...
</optgroup>
</select>
</div>
我完全控制了在Selectbox中添加了哪些选项和多少个选项,我只是喜欢在某些标准下为清晰的目的进行分组(仅此示例仅是第一个2和第二3,但不一定取决于迭代器)。但是我不能使用任何框架/库,它必须必须是纯JavaScript。我也知道createElement()方法,但是我正在使用"选项"属性,只是想知道它是否可以使用。
如果不可能,我想知道我必须动态创建optgroup的替代方案,否则我只会完全使用OptGroup进行放弃。
您需要创建optgroup
元素并将options
附加到该元素上(然后将该optgroup
元素附加到select
元素)。
这是一个有效的示例:
var demo = document.getElementById("d").children[0];
var optGroup = document.createElement('optgroup')
optGroup.setAttribute('label', 'some value')
for (var i = 1; i <= 5; i++)
{
// this will in this case auto-select and default-select the third option
optGroup.appendChild(new Option("Value: " + i, i, i == 3, i == 3))
}
demo.appendChild(optGroup)
var optGroup = document.createElement('optgroup')
optGroup.setAttribute('label', 'some other value')
for (var i = 6; i <= 10; i++)
{
// this will in this case auto-select and default-select the third option
optGroup.appendChild(new Option("Value: " + i, i, i == 3, i == 3))
}
demo.appendChild(optGroup)
<div id="d">
<select></select>
</div>
Option()
构造函数是一个非标准的构造函数,但是几乎每个浏览器都具有它。另一方面,<optgroup>
元素没有这样的构造函数,因此为了创建它,您必须使用document.createElement
。