使用jQuery向下拉列表中添加选项的最简单方法是什么?

这行吗?

$("#mySelect").append('<option value=1>My option</option>');

当前回答

var select = $('#myselect');
var newOptions = {
                'red' : 'Red',
                'blue' : 'Blue',
                'green' : 'Green',
                'yellow' : 'Yellow'
            };
$('option', select).remove();
$.each(newOptions, function(text, key) {
    var option = new Option(key, text);
    select.append($(option));
});

其他回答

这只是最佳性能的快速要点

总是当你处理很多选项时,建立一个大字符串,然后将其添加到“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');

您可以使用以下语法添加选项,也可以访问jQuery中的way handle选项以了解更多详细信息。

$('#select').append($('<option>',{value:1,text:'One'}));$('#select').append('<option value=“1”>一个</option>');var option=新选项(文本,值)$('#select').append($(选项));

$('#select_id').append($('<option>',{ value: v, text: t }));

Try

mySelect.innerHTML+= '<option value=1>My option</option>';

btn.onclick=_=>mySelect.innerHTML+=`<optionselected>${+newDate}</option>`<button id=“btn”>添加选项</button><select id=“mySelect”></select>

这在IE8中不起作用(但在FF中起作用):

$("#selectList").append(new Option("option text", "value"));

这确实有效:

var o = new Option("option text", "value");
/// jquerify the DOM object 'o' so we can use the html method
$(o).html("option text");
$("#selectList").append(o);