以编程方式创建选择列表

sis*_*sko 41 jquery selectlist

有没有人知道一种以编程方式创建HTML选择列表的技术,包括使用JQuery的选项?

js1*_*568 108

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));
});
Run Code Online (Sandbox Code Playgroud)


rid*_*rid 13

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


ric*_*ier 6

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

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


Nat*_*son 5

这很简单:

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