使用jQuery向<select>添加选项?

option使用jQuery向下拉菜单添加的最简单方法是什么?

这样行吗?

$("#mySelect").append('<option value=1>My option</option>');
梅A飞云2020/03/11 11:59:45

U can try below code to append to option

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

    <script>
          $("#mySelect").append($("<option></option>").val("1").html("My enter code hereoption"));
    </script>
Stafan村村达蒙2020/03/11 11:59:45
$(function () {
     var option = $("<option></option>");
     option.text("Display text");
     option.val("1");
     $("#Select1").append(option);
});

If you getting data from some object, then just forward that object to function...

$(function (product) {
     var option = $("<option></option>");
     option.text(product.Name);
     option.val(product.Id);
     $("#Select1").append(option);
});

Name and Id are names of object properties...so you can call them whatever you like...And ofcourse if you have Array...you want to build custom function with for loop...and then just call that function in document ready...Cheers

Jim米亚西里2020/03/11 11:59:45

Not mentioned in any answer but useful is the case where you want that option to be also selected, you can add:

var o = new Option("option text", "value");
o.selected=true;
$("#mySelect").append(o);
谷若汐2020/03/11 11:59:45

那很好。

如果添加多个选项元素,我建议执行一次附加操作,而不是在每个元素上执行附加操作。