Bạn có thể đạt được điều này với một for
vòng lặp đơn giản :
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);
}
Bản demo của Fiddle .
JS Perf so sánh câu trả lời của cả tôi và Sime Vidas , vì tôi nghĩ rằng anh ta trông có vẻ dễ hiểu / trực quan hơn tôi một chút và tôi tự hỏi làm thế nào điều đó sẽ chuyển thành việc thực hiện. Theo Chromium 14 / Ubuntu 11.04 của tôi có phần nhanh hơn, các trình duyệt / nền tảng khác có thể có kết quả khác nhau mặc dù.
Đã chỉnh sửa để phản hồi nhận xét từ OP:
[Làm thế nào] [tôi] áp dụng điều này cho nhiều hơn một yếu tố?
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);
Bản demo của Fiddle .
Và cuối cùng (sau một thời gian trì hoãn ...), một cách tiếp cận mở rộng nguyên mẫu của HTMLSelectElement
chuỗi để xâu chuỗi populate()
hàm, như một phương thức, đến nút 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
});
Bản demo của Fiddle .
Người giới thiệu: