你可以通过一个简单的方法来实现这一点for
loop:
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 小提琴演示 http://jsfiddle.net/davidThomas/NX3ac/.
JS Perf http://jsperf.com/我的和的比较西姆·维达斯的回答 http://jsperf.com/comparison-of-loops,运行,因为我认为他的看起来比我的更容易理解/直观,我想知道这将如何转化为实现。根据 Chromium 14/Ubuntu 11.04,我的速度更快,但其他浏览器/平台可能会产生不同的结果。
Edited回应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 小提琴演示 http://jsfiddle.net/davidThomas/NX3ac/1/.
最后(在相当长的延迟之后......),一种扩展原型的方法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 小提琴演示 http://jsfiddle.net/davidThomas/NX3ac/148/.
参考:
-
node.appendChild() https://developer.mozilla.org/en/DOM/node.appendChild.
-
document.getElementById() https://developer.mozilla.org/en/DOM/document.getElementById.
-
element.innerHTML https://developer.mozilla.org/en/DOM/element.innerHTML.