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

这行吗?

$("#mySelect").append('<option value=1>My option</option>');

当前回答

Try

mySelect.innerHTML+= '<option value=1>My option</option>';

btn.onclick=_=>mySelect.innerHTML+=`<optionselected>${+newDate}</option>`<button id=“btn”>添加选项</button><select id=“mySelect”></select>

其他回答

如果有人来这里寻找添加数据财产选项的方法

使用属性

var option = $('<option>', { value: 'the_value', text: 'some text' }).attr('family', model.family);

使用数据-版本1.2.3

var option = $('<option>', { value: 'the_value', text: 'some text' }).data('misc', 'misc-value);

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

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

您可以尝试以下代码附加到选项

  <select id="mySelect"></select>

    <script>
          $("#mySelect").append($("<option></option>").val("1").html("My enter code hereoption"));
    </script>

这在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);

您可以在ES6中执行此操作:

$.each(json, (i, val) => {
    $('.js-country-of-birth').append(`<option value="${val.country_code}"> ${val.country} </option>`);
  });