使用jQuery向下拉列表中添加选项的最简单方法是什么?
这行吗?
$("#mySelect").append('<option value=1>My option</option>');
使用jQuery向下拉列表中添加选项的最简单方法是什么?
这行吗?
$("#mySelect").append('<option value=1>My option</option>');
当前回答
如果您在select中有optgroup,则在DOM中出现错误。
我认为最好的方法是:
$("#select option:last").after($('<option value="1">my option</option>'));
其他回答
您可以在ES6中执行此操作:
$.each(json, (i, val) => {
$('.js-country-of-birth').append(`<option value="${val.country_code}"> ${val.country} </option>`);
});
如果要在选择中的特定索引处插入新选项:
$("#my_select option").eq(2).before($('<option>', {
value: 'New Item',
text: 'New Item'
}));
这将在选择中插入“新项目”作为第三个项目。
就我个人而言,我更喜欢用这种语法附加选项:
$('#mySelect').append($('<option>', {
value: 1,
text: 'My option'
}));
如果要从项目集合中添加选项,可以执行以下操作:
$.each(items, function (i, item) {
$('#mySelect').append($('<option>', {
value: item.value,
text : item.text
}));
});
这很简单:
$('#select_id').append('<option value="five" selected="selected">Five</option>');
or
$('#select_id').append($('<option>', {
value: 1,
text: 'One'
}));
这在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);