添加要使用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贡献1829条经验 获得超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);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贡献1816条经验 获得超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);}
它被用作文档的轻量级版本,用于存储由节点组成的文档部分,就像标准文档一样。关键的区别在于,由于文档片段不是实际DOM结构的一部分,因此对该片段所做的更改不会影响文档,不会导致重流,也不会导致更改时可能发生的任何性能影响。
添加回答
举报
0/150
提交
取消
