如何给一个数组作为选择元素的选项? [英] how can I give an array as options to select element?
本文介绍了如何给一个数组作为选择元素的选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的HTML页面上有一个select元素.我想用数组填充它.因为我们可以在动作脚本中为comboBox提供一个数组作为数据提供者.我执行以下操作
I have a select element on my HTML page. I want to populate it with an array. as we can give an array as dataprovider to comboBox in action script. I do the following
以HTML ...
<table>
<tr>
<td>
<label>Recording Mode:</label>
</td>
<td>
<select id="rec_mode">
</select>
</td>
</tr>
</table>
在javascript中...
in javascript...
var videoSrcArr = new Array("option1", "option2", "option3", "option4", "option5");
如何在用VideoSrcArr加载页面时填充rec_mode元素?谢谢
how can I populate rec_mode element when page is loaded with VideoSrcArr? Thanks
推荐答案
我强烈建议您使用以下格式:
I highly recommend you use a format like the following:
var options =
[
{
"text" : "Option 1",
"value" : "Value 1"
},
{
"text" : "Option 2",
"value" : "Value 2",
"selected" : true
},
{
"text" : "Option 3",
"value" : "Value 3"
}
];
var selectBox = document.getElementById('rec_mode');
for(var i = 0, l = options.length; i < l; i++){
var option = options[i];
selectBox.options.add( new Option(option.text, option.value, option.selected) );
}
您不必遇到必须选择默认选项的问题,并且可以轻松地动态生成options数组.
You don't run in to the problem of having to select a default option and you can easily generate the options array dynamically.
-更新-
上述代码的ES6版本:
ES6 version of the above code:
let optionList = document.getElementById('rec_mode').options;
let options = [
{
text: 'Option 1',
value: 'Value 1'
},
{
text: 'Option 2',
value: 'Value 2',
selected: true
},
{
text: 'Option 3',
value: 'Value 3'
}
];
options.forEach(option =>
optionList.add(
new Option(option.text, option.value, option.selected)
)
);
这篇关于如何给一个数组作为选择元素的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文