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

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

其他回答

function LoadCategories() {
    var data = [];
    var url = '@Url.Action("GetCategories", "InternalTables")';
    $.getJSON(url, null, function (data) {
        data = $.map(data, function (item, a) {
            return "<option value=" + item.Value + ">" + item.Description + "</option>";
        });
        $("#ddlCategory").html('<option value="0">Select</option>');
        $("#ddlCategory").append(data.join(""));
    });
}

我使用jquery插件的选择框。它把你的例子变成:

$('#idofselect').ajaxAddOption('/Admin/GetFolderList/', {}, false);

对于像我这样的JavaScript新手,更不用说JQuery了,JavaScript的方式是:

result.forEach(d=>$("#dropdown").append(new Option(d,d)))

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));
    });
  })

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

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