慕虎7371278
2019-07-17 15:40:48
添加要使用javascript進行選擇的選項我希望這個javascript在一個帶有id=“mainSelect”的SELECT中創(chuàng)建12到100的選項,因為我不想手動創(chuàng)建所有的選項標記。你能給我一些指點嗎?謝謝function selectOptionCreate() {
var age = 88;
line = "";
for (var i = 0; i < 90; i++) {
line += "<option>";
line += age + i;
line += "</option>";
}
return line;}
3 回答

千巷貓影
TA貢獻1829條經(jīng)驗 獲得超7個贊
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);}
編輯
[我]如何將其應用于多個元素?
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()
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貢獻1816條經(jīng)驗 獲得超6個贊
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);}
它被用作文檔的輕量級版本,用于存儲由節(jié)點組成的文檔部分,就像標準文檔一樣。關鍵的區(qū)別在于,由于文檔片段不是實際DOM結(jié)構的一部分,因此對該片段所做的更改不會影響文檔,不會導致重流,也不會導致更改時可能發(fā)生的任何性能影響。
添加回答
舉報
0/150
提交
取消