使用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>'));
其他回答
为什么不简单呢?
$('<option/>')
.val(optionVal)
.text('some option')
.appendTo('#mySelect')
此处测试:
for(设i=0;i<10;i++){$('<option/>').val(i).text('option'+i).appendTo('#mySelect')}<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><select id=“mySelect”></select>
您可以在ES6中执行此操作:
$.each(json, (i, val) => {
$('.js-country-of-birth').append(`<option value="${val.country_code}"> ${val.country} </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>
如果要在选择中的特定索引处插入新选项:
$("#my_select option").eq(2).before($('<option>', {
value: 'New Item',
text: 'New Item'
}));
这将在选择中插入“新项目”作为第三个项目。
var select = $('#myselect');
var newOptions = {
'red' : 'Red',
'blue' : 'Blue',
'green' : 'Green',
'yellow' : 'Yellow'
};
$('option', select).remove();
$.each(newOptions, function(text, key) {
var option = new Option(key, text);
select.append($(option));
});