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

这行吗?

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

当前回答

当您附加选项并使用jqueryvalidate时,我们发现了一些问题。您必须在选择多个列表中单击一个项目。您将添加此代码以处理:

$("#phonelist").append("<option value='"+ 'yournewvalue' +"' >"+ 'yournewvalue' +"</option>");

$("#phonelist option:selected").removeAttr("selected"); // add to remove lase selected

$('#phonelist option[value=' + 'yournewvalue' + ']').attr('selected', true); //add new selected

其他回答

如果要在选择中的特定索引处插入新选项:

$("#my_select option").eq(2).before($('<option>', {
    value: 'New Item',
    text: 'New Item'
}));

这将在选择中插入“新项目”作为第三个项目。

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

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

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

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

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

我喜欢使用非jquery方法:

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

这个怎么样

var numbers = [1, 2, 3, 4, 5];
var option = '';

for (var i=0;i<numbers.length;i++){
     option += '<option value="'+ numbers[i] + '">' + numbers[i] + '</option>';
    }

    $('#items').append(option);