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

这行吗?

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

当前回答

仅通过单线

   $.each(result, function (k,v) {
                         **if(k == selectedMonthNumber) var selectedMonth = 'selected'; else var selectedMonth = '';**
                             $("#periodMonth").append($('<option>', {
                                 value: k,
                                 text: v,
                                 **selected: selectedMonth**
                         }));
                    })

其他回答

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

使用属性

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

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

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

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

如果您在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>

无论出于何种原因执行$(“#myselect”).append(新选项(“text”,“text”));在IE7中对我不起作用+

我必须使用$(“#myselect”).html(“<option value='text'>text</option>”);