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

这行吗?

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

当前回答

无论出于何种原因执行$(“#myselect”).append(新选项(“text”,“text”));在IE7中对我不起作用+

我必须使用$(“#myselect”).html(“<option value='text'>text</option>”);

其他回答

选项1-

你可以试试这个-

$('#selectID').append($('<option>',
 {
    value: value_variable,
    text : text_variable
}));

像这样-

对于(i=0;i<10;i++){ $('#mySelect').append($('<option>',{值:i,text:“选项”+i}));}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js“></script><select id='mySelect'></select>

选项2-

或者试试这个-

$('#selectID').append( '<option value="'+value_variable+'">'+text_variable+'</option>' );

像这样-

对于(i=0;i<10;i++){ $('#mySelect').append('<option value=“'+i+'”>'+'option'+i+'</option>');}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js“></script><select id='mySelect'></select>

我喜欢使用非jquery方法:

mySelect.add(new Option('My option', 1));

这很简单:

$('#select_id').append('<option value="five" selected="selected">Five</option>');

or

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

您可以尝试以下代码附加到选项

  <select id="mySelect"></select>

    <script>
          $("#mySelect").append($("<option></option>").val("1").html("My enter code hereoption"));
    </script>

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

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