答案 0 :(得分:1)
您可以使用此函数动态生成选项,方法是将选项数量传递给generate,选择器以放置所选选项的选项和索引:
var ns = {
genOpts: function(num, sel, selOpt) {
$(sel).empty();
for (var i = 0; i < num; i++) {
$('<option>', {
text: 'New Option ' + i,
value: 'new_option_' + i
}).appendTo(sel);
}
$(sel).find('option').eq(selOpt).attr('selected', 'selected');
}
};
ns.genOpts(5, ".selectOptions", 3);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control selectOptions">
<option>Default Option 1</option>
<option selected>Default Option 2</option>
<option>Default Option 3</option>
</select>
&#13;
答案 1 :(得分:1)
尝试使用$.map()
,String.prototype.toLowerCase()
,String.prototype.replace()
与RegExp
/\s/g
匹配myNewOptions
数组中的字词之间的空格字符,{{1 },.outerHTML
;创建变量.append()
以将第四个selected
已创建的属性option
设置为selected
true
&#13;
var myNewOptions = [
"New Option 1",
"New Option 2",
"New Option 3",
"New Option 4",
"New Option 5"
],
selected = 3;
var options = $.map(myNewOptions, function(opts, index) {
return $("<option>", {
value: opts.toLowerCase().replace(/\s/g, "_"),
html: opts,
selected: index === selected ? true : false
})[0].outerHTML
});
$(".form-control").empty().append(options);
&#13;