我经常看到的示例似乎不是最优的,因为它涉及到连接字符串,这似乎不是jQuery。它通常是这样的:

$.getJSON("/Admin/GetFolderList/", function(result) {
    for (var i = 0; i < result.length; i++) {
        options += '<option value="' + result[i].ImageFolderID + '">' + result[i].Name + '</option>';
    }
});

有没有更好的办法?


当前回答

安德里亚斯·格雷奇很接近……它实际上是this(注意对this的引用而不是循环中的项):

var $dropdown = $("#dropdown");
$.each(result, function() {
    $dropdown.append($("<option />").val(this.ImageFolderID).text(this.Name));
});

其他回答

或者:

var options = $("#options");
$.each(data, function() {
    options.append(new Option(this.text, this.value));
});

我发现这是从jquery网站工作

$.getJSON( "/Admin/GetFolderList/", function( data ) {
  var options = $("#dropdownID");
  $.each( data, function(key, val) {
    options.append(new Option(key, val));
  });
});

我一直在使用jQuery和调用一个函数来填充下拉列表。

function loadDropDowns(name,value)
{
   var ddl = "#Categories";
   $(ddl).append('<option value="' + value + '">' + name + "</option>'");
}

ES6的其他方法

fetch('https://restcountries.eu/rest/v1/all')
  .then((response) => {
    return response.json()
  })
  .then((countries) => {
    var options = document.getElementById('someSelect');
    countries.forEach((country) => {
      options.appendChild(new Option(country.name, country.name));
    });
  })

最快的方法是:

 $.getJSON("/Admin/GetFolderList/", function(result) {
        var optionsValues = '<select>';
        $.each(result, function(item) {
            optionsValues += '<option value="' + item.ImageFolderID + '">' + item.Name + '</option>';
        });
        optionsValues += '</select>';
        var options = $('#options');
        options.replaceWith(optionsValues);
    });

根据这个链接是最快的方法,因为在进行任何类型的DOM插入时,都将所有内容包装在一个元素中。