使用jQuery向下拉列表中添加选项的最简单方法是什么?
这行吗?
$("#mySelect").append('<option value=1>My option</option>');
使用jQuery向下拉列表中添加选项的最简单方法是什么?
这行吗?
$("#mySelect").append('<option value=1>My option</option>');
当前回答
无论出于何种原因执行$(“#myselect”).append(新选项(“text”,“text”));在IE7中对我不起作用+
我必须使用$(“#myselect”).html(“<option value='text'>text</option>”);
其他回答
无论出于何种原因执行$(“#myselect”).append(新选项(“text”,“text”));在IE7中对我不起作用+
我必须使用$(“#myselect”).html(“<option value='text'>text</option>”);
如果您在select中有optgroup,则在DOM中出现错误。
我认为最好的方法是:
$("#select option:last").after($('<option value="1">my option</option>'));
$('#mySelect').empty().append('<option value=1>My option</option>').selectmenu('refresh');
Try
mySelect.innerHTML+= '<option value=1>My option</option>';
btn.onclick=_=>mySelect.innerHTML+=`<optionselected>${+newDate}</option>`<button id=“btn”>添加选项</button><select id=“mySelect”></select>
为了提高性能,您应该尝试只更改DOM一次,如果要添加许多选项,则更应该如此。
var html = '';
for (var i = 0, len = data.length; i < len; ++i) {
html.join('<option value="' + data[i]['value'] + '">' + data[i]['label'] + '</option>');
}
$('#select').append(html);