您可以通过一个简单的
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 Perf比较了我和imeVidas的答案,是因为我认为他的表情比我的看起来更容易理解/直观,而且我想知道这将如何转化为实现。根据Chromium14/Ubuntu11.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);最后,(经过相当长的延迟之后),一种方法扩展了原型,
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});


