呼啦一陣風
2019-07-27 15:15:35
添加要使用javascript進行選擇的選項我希望這個javascript在一個帶有id=“mainSelect”的SELECT中創建12到100的選項,因為我不想手動創建所有的選項標記。你能給我一些指點嗎?謝謝function selectOptionCreate() {
var age = 88;
line = "";
for (var i = 0; i < 90; i++) {
line += "<option>";
line += age + i;
line += "</option>";
}
return line;}
3 回答
月關寶盒
TA貢獻1772條經驗 獲得超5個贊
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
編輯
[我]如何將其應用于多個元素?
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);HTMLSelectElementpopulate()
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});
千萬里不及你
TA貢獻1784條經驗 獲得超9個贊
var elMainSelect = document.getElementById('mainSelect');function selectOptionsCreate() {
var frag = document.createDocumentFragment(),
elOption;
for (var i=12; i<101; ++i) {
elOption = frag.appendChild(document.createElement('option'));
elOption.text = i;
}
elMainSelect.appendChild(frag);}
它被用作文檔的輕量級版本,用于存儲由節點組成的文檔部分,就像標準文檔一樣。關鍵的區別在于,由于文檔片段不是實際DOM結構的一部分,因此對該片段所做的更改不會影響文檔,不會導致重流,也不會導致更改時可能發生的任何性能影響。
添加回答
舉報
0/150
提交
取消
