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

这行吗?

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

当前回答

就我个人而言,我更喜欢用这种语法附加选项:

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

如果要从项目集合中添加选项,可以执行以下操作:

$.each(items, function (i, item) {
    $('#mySelect').append($('<option>', { 
        value: item.value,
        text : item.text 
    }));
});

其他回答

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

就我个人而言,我更喜欢用这种语法附加选项:

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

如果要从项目集合中添加选项,可以执行以下操作:

$.each(items, function (i, item) {
    $('#mySelect').append($('<option>', { 
        value: item.value,
        text : item.text 
    }));
});

如果有人来这里寻找添加数据财产选项的方法

使用属性

var option = $('<option>', { value: 'the_value', text: 'some text' }).attr('family', model.family);

使用数据-版本1.2.3

var option = $('<option>', { value: 'the_value', text: 'some text' }).data('misc', 'misc-value);

这在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);

这很好。

如果添加多个选项元素,我建议执行一次追加,而不是对每个元素执行追加。