使用jQuery向下拉列表中添加选项的最简单方法是什么?
这行吗?
$("#mySelect").append('<option value=1>My option</option>');
使用jQuery向下拉列表中添加选项的最简单方法是什么?
这行吗?
$("#mySelect").append('<option value=1>My option</option>');
当前回答
可以使用文本附加和设置“值”属性:
$("#id").append($('<option></option>').attr("value", '').text(''));
$("#id").append($('<option></option>').attr("value", '4').text('Financial Institutions'));
其他回答
答案中没有提及,但很有用。如果您希望也选择该选项,您可以添加:
var o = new Option("option text", "value");
o.selected=true;
$("#mySelect").append(o);
无论出于何种原因执行$(“#myselect”).append(新选项(“text”,“text”));在IE7中对我不起作用+
我必须使用$(“#myselect”).html(“<option value='text'>text</option>”);
这很简单:
$('#select_id').append('<option value="five" selected="selected">Five</option>');
or
$('#select_id').append($('<option>', {
value: 1,
text: 'One'
}));
这个怎么样
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);
如果要在选择中的特定索引处插入新选项:
$("#my_select option").eq(2).before($('<option>', {
value: 'New Item',
text: 'New Item'
}));
这将在选择中插入“新项目”作为第三个项目。