月关宝盒
你可以用一个简单的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 Fiddle演示.JS Perf我的和我的比较Sime Vidas的回答,因为我认为他的看起来比我的更容易理解/直观,我想知道这将如何转化为实现。根据Chromium14/Ubuntu11.04的说法,我的速度有点快,其他浏览器/平台可能会有不同的结果。编辑针对执行部分的评论:[我]如何将其应用于多个元素?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 Fiddle演示.最后(经过很长时间的延迟.),一种扩展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 Fiddle演示.参考资料:node.appendChild().document.getElementById().element.innerHTML.