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

这行吗?

$("#mySelect").append('<option value=1>My option</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'
}));

这将在选择中插入“新项目”作为第三个项目。

选项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>

我就是这样做的,用一个按钮添加每个选择标记。

$(document).on("click","#button",function() {
   $('#id_table_AddTransactions').append('<option></option>')
}

为了提高性能,您应该尝试只更改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);

这很简单:

$('#select_id').append('<option value="five" selected="selected">Five</option>');

or

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