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

function selectOptionCreate() {

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

  return line;
}

当前回答

参见:用jQuery从数组中添加选项的最佳方法是什么?

$('#mySelect')
      .append($('<option>', { value : key })
      .text(value)); 

其他回答

For(设I = 12;我< 101;我+ +){ 让HTML = "" HTML += ' <选项值= " ${我}" > ${我}> < /选项 ` mainSelect。innerHTML += html } const mainSelect = document.getElementById("mainSelect") 这是一种非常简单易懂的解决问题的方法!希望它能起作用:)

参见:用jQuery从数组中添加选项的最佳方法是什么?

$('#mySelect')
      .append($('<option>', { value : key })
      .text(value)); 

你可以用一个简单的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小提琴演示。

JS性能比较我和Sime Vidas的答案,运行是因为我认为他看起来比我的更容易理解/直观,我想知道这将如何转化为实现。根据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小提琴演示。

引用:

node.appendChild()。 . getelementbyid()。 element.innerHTML。

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

for (var age = 12; age <= 100; age++) {
  selectElement.add(new Option(age, age));
}


Your age: <select id="ageselect"><option value="">Please select</option></select>

注意,该值作为第二个参数添加到new Option中

当您创建一个新的Option对象时,有两个参数要传递:第一个是您想要的文本 出现在列表中,第二个是要分配给该选项的值。

var myNewOption = new Option("TheText", "TheValue");

然后你只需将这个Option对象赋值给一个空数组元素,例如:

document.theForm.theSelectObject.options[0] = myNewOption;