使用jQuery向下拉列表中添加选项的最简单方法是什么?
这行吗?
$("#mySelect").append('<option value=1>My option</option>');
使用jQuery向下拉列表中添加选项的最简单方法是什么?
这行吗?
$("#mySelect").append('<option value=1>My option</option>');
当前回答
有两种方法。您可以使用这两种方法中的任何一种。
第一:
$('#waterTransportationFrom').append('<option value="select" selected="selected">Select From Dropdown List</option>');
第二:
$.each(dataCollecton, function(val, text) {
options.append($('<option></option>').val(text.route).html(text.route));
});
其他回答
我喜欢使用非jquery方法:
mySelect.add(new Option('My option', 1));
为什么不简单呢?
$('<option/>')
.val(optionVal)
.text('some option')
.appendTo('#mySelect')
此处测试:
for(设i=0;i<10;i++){$('<option/>').val(i).text('option'+i).appendTo('#mySelect')}<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><select id=“mySelect”></select>
有两种方法。您可以使用这两种方法中的任何一种。
第一:
$('#waterTransportationFrom').append('<option value="select" selected="selected">Select From Dropdown List</option>');
第二:
$.each(dataCollecton, function(val, text) {
options.append($('<option></option>').val(text.route).html(text.route));
});
这只是最佳性能的快速要点
总是当你处理很多选项时,建立一个大字符串,然后将其添加到“select”中以获得最佳性能
f.g.
var$mySelect=$('#mySelect');var str=“”;
$.each(items, function (i, item) {
// IMPORTANT: no selectors inside the loop (for the best performance)
str += "<option value='" + item.value + "'> " + item.text + "</option>";
});
// you built a big string
$mySelect.html(str); // <-- here you add the big string with a lot of options into the selector.
$mySelect.multiSelect('refresh');
甚至更快
var str = "";
for(var i; i = 0; i < arr.length; i++){
str += "<option value='" + item[i].value + "'> " + item[i].text + "</option>";
}
$mySelect.html(str);
$mySelect.multiSelect('refresh');
答案中没有提及,但很有用。如果您希望也选择该选项,您可以添加:
var o = new Option("option text", "value");
o.selected=true;
$("#mySelect").append(o);