添加选项以使用 javascript 进行选择

新手上路,请多包涵

我希望这个 javascript 在 id=“mainSelect” 的选择中创建从 12 到 100 的选项,因为我不想手动创建所有选项标签。你能给我一些指示吗?谢谢

function selectOptionCreate() {

  var age = 88;
  line = "";
  for (var i = 0; i < 90; i++) {
    line += "<option>";
    line += age + i;
    line += "</option>";
  }

  return line;
}

原文由 jacktheripper 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 685
2 个回答

您可以通过一个简单 for 循环来实现这一点:

 var min = 12,
 max = 100,
 select = document.getElementById('selectElementId');

 for (var i = min; i<=max; i++){
 var opt = document.createElement('option');
 opt.value = i;
 opt.innerHTML = i;
 select.appendChild(opt);
 }

JS 小提琴演示

我的和 Sime Vidas 的答案JS Perf 比较,运行是因为我认为他看起来比我的更易于理解/直观,我想知道这将如何转化为实施。根据 Chromium 14/Ubuntu 11.04,我的速度要快一些,但其他浏览器/平台可能会产生不同的结果。


针对 OP 的评论进行了 编辑

[如何] [我] 将其应用于多个元素?

 function populateSelect(target, min, max){
 if (!target){
 return false;
 }
 else {
 var min = min || 0,
 max = max || min + 100;

 select = document.getElementById(target);

 for (var i = min; i<=max; i++){
 var opt = document.createElement('option');
 opt.value = i;
 opt.innerHTML = i;
 select.appendChild(opt);
 }
 }
 }
 // calling the function with all three values:
 populateSelect('selectElementId',12,100);

 // calling the function with only the 'id' ('min' and 'max' are set to defaults):
 populateSelect('anotherSelect');

 // calling the function with the 'id' and the 'min' (the 'max' is set to default):
 populateSelect('moreSelects', 50);

JS 小提琴演示

最后(经过相当长的延迟……),一种扩展 HTMLSelectElement 原型的方法,以便将 populate() 函数作为一种方法链接到 DOM 节点:

 HTMLSelectElement.prototype.populate = function (opts) {
 var settings = {};

 settings.min = 0;
 settings.max = settings.min + 100;

 for (var userOpt in opts) {
 if (opts.hasOwnProperty(userOpt)) {
 settings[userOpt] = opts[userOpt];
 }
 }

 for (var i = settings.min; i <= settings.max; i++) {
 this.appendChild(new Option(i, i));
 }
 };

 document.getElementById('selectElementId').populate({
 'min': 12,
 'max': 40
 });

JS 小提琴演示

参考:

原文由 David Thomas 发布,翻译遵循 CC BY-SA 3.0 许可协议

最简洁直观的方法是:

 var selectElement = document.getElementById('ageselect');

for (var age = 12; age <= 100; age++) {
  selectElement.add(new Option(age));
}
 Your age: <select id="ageselect"><option value="">Please select</option></select>

您还可以区分名称和值,或者在列表的开头添加项目,并为所用函数添加附加参数:

HTMLSelect Element .add (item[, before]);

新选项(文本、值、默认选择、已选择);

原文由 user 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题