如何将数组作为选择元素的选项?

Sar*_*med 17 html javascript html5

我的HTML页面上有一个select元素.我想用数组填充它.因为我们可以将一个数组作为数据提供者给动作脚本中的comboBox.我做了以下事情

在HTML中......

<table>
  <tr>
    <td>
      <label>Recording Mode:</label>
    </td>
    <td>
      <select id="rec_mode">        
      </select>
    </td>
  </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

在javascript中......

var videoSrcArr = new Array("option1", "option2", "option3", "option4", "option5");
Run Code Online (Sandbox Code Playgroud)

当使用VideoSrcArr加载页面时,如何填充rec_mode元素?谢谢

THE*_*had 18

我强烈建议您使用如下格式:

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) );
}
Run Code Online (Sandbox Code Playgroud)

您没有遇到必须选择默认选项的问题,您可以轻松地动态生成选项数组.

- 更新 -

以上代码的ES6版本:

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)
  )
);
Run Code Online (Sandbox Code Playgroud)

  • 如何获取选择值? (2认同)

ame*_*ote 5

我建议使用对象而不是数组,它将是非常有用的,并以尊重的方式与标准.原因是我们可以通过"键"索引对象并获得"值".要显示内容并重置它们,您可以按照此 注释进行操作

检查一下

<!DOCTYPE html>
<html>
<body>
<table>
  <tr>
    <td>
      <label>Recording Mode:</label>
    </td>
    <td>
      <select id="rec_mode">        
      </select>
    </td>
  </tr>
</table>
</body>
<script>
var myobject = {
    ValueA : 'Text A',
    ValueB : 'Text B',
    ValueC : 'Text C'
};
var select = document.getElementById("rec_mode");
for(index in myobject) {
    select.options[select.options.length] = new Option(myobject[index], index);
}

</script>
</html>
Run Code Online (Sandbox Code Playgroud)


JDe*_*Dev 5

这是用数组填充组合框的最简单方法。

var j = new Array("option1","option2","option3","option4","option5"),    
var options = '';

for (var i = 0; i < j.length; i++) {
   options += '<option value="' + j[i]+ '">' + j[i] + '</option>';
}
$("#rec_mode").html(options);
Run Code Online (Sandbox Code Playgroud)