jQuery 以编程方式创建选择列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6601952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:06:17  来源:igfitidea点击:

Programmatically create select list

jqueryselectlist

提问by sisko

Does anyone know of a technique to programmatically create an HTML select list including options using JQuery?

有谁知道使用 JQuery 以编程方式创建包含选项的 HTML 选择列表的技术?

回答by js1568

var arr = [
  {val : 1, text: 'One'},
  {val : 2, text: 'Two'},
  {val : 3, text: 'Three'}
];

var sel = $('<select>').appendTo('body');
$(arr).each(function() {
 sel.append($("<option>").attr('value',this.val).text(this.text));
});

回答by rid

var s = $('<select/>');
var o = [1, 2, 3];
for (var i in o) {
    s.append($('<option/>').html(o[i]));
}
$('body').append(s);

回答by rich tier

I know this is old, but what the hey:

我知道这是旧的,但是嘿嘿:

$selectBox.html($.map(myArray, function(){
    return $('<option/>', {text: this});
}));

回答by Nathan Anderson

This is very straight forward to do:

这是非常直接的:

var selectList = "<select name='numbers'>";
for (var x = 0; x < 10; x++) {
    selectList += "<option>" + x + "</option>";
}
selectList += "</select>";
$('#my-container').html(selectList);

回答by K.Alex

If you have already <select> list somewhere in DOM, reuse it and make it empty from previous user interactions...

如果您已经在 DOM 中的某处有 <select> 列表,请重用它并将其从以前的用户交互中清空...

// Call existing list, chain empty()
var my_list = $("#my_list").empty();

// Build list
$(my_arr).each(function() {
 my_list.append($(<option>").attr(\'value\',this.item_id).text(this.item_name));
});

回答by Gene Bo

Here's a variation - based on previous answers in this thread - where all but the select-input optionscan be specified via an input JSON object:

这是一个变体 - 基于此线程中先前的答案 - 除了选择输入选项之外的所有选项都可以通过输入 JSON 对象指定:

Would be interesting to see if the options array can somehow be specified in that JSON input?

看看是否可以在该 JSON 输入中以某种方式指定选项数组会很有趣吗?

    var fruitListProfile = {
        id : someKey,
        class : 'fruit_list',
        style : 'margin-right: 20px; '
    };

    var selectInput = $('<select/>', fruitListProfile);

    var fruitOptions = ['apple', 'cherry', 'kiwi'];
    for (var i in fruitOptions) {
        selectInput.append($('<option/>').html(fruitOptions[i]));
    }

回答by Mike Volmar

Here is another version of an answer to the question using ajax to fetch a json response used to create the select list with key value pairs

这是使用 ajax 获取用于创建带有键值对的选择列表的 json 响应的问题答案的另一个版本

        $.ajax({
        type: 'post',
        url: 'include/parser.php',
        data: {                     
            mode: 'getSubtypes',
            type: type
        },
        success: function (response) {
            var mySubtype = document.getElementById("Component");
            var components = $.parseJSON(response);

            var selectList = document.createElement("select");
            selectList.id = "subtype";
            selectList.name = "subtype";
            mySubtype.appendChild(selectList);
            $('#subtype').append('<option value="">Select ...</option>');
            $.each(components, function(k, v) {
                var option = new Option(v, k); 
                $('#subtype').append($(option));               
            });
        }
    });        

回答by Denis Lightman

I think it's simpler.IMHO.

我认为它更简单。恕我直言。

 arr.map(x => ($("YOUR SELECTOR").append(`<option value="${x}">${x}</option>`)));