使用jQuery向添加选项?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点</p>

4个回答
梅A飞云 2020.03.11

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
$(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

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

那很好。

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android