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

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

有没有更好的办法?


当前回答

这是我做的一个关于change的例子,我在second select中获得了first select的子元素

jQuery(document).ready(function($) {
$('.your_select').change(function() {
    $.ajaxSetup({
        headers:{'X-CSRF-TOKEN': $("meta[name='csrf-token']").attr('content')}
    });

    $.ajax({
        type:'POST',
        url: 'Link',
        data:{
          'id': $(this).val()
        },
        success:function(r){
          $.each(r, function(res) {
                console.log(r[res].Nom);
                 $('.select_to_populate').append($("<option />").val(r[res].id).text(r[res].Nom));
            });
        },error:function(r) {
          alert('Error');
        }
    });
});

});在这里输入代码

其他回答

下面是填充id为“FolderListDropDown”的下拉列表的Jquery方法。

$.getJSON("/Admin/GetFolderList/", function(result) {
    for (var i = 0; i < result.length; i++) {
        var elem = $("<option></option>");
        elem.attr("value", result[i].ImageFolderID);
        elem.text(result[i].Name);
        elem.appendTo($("select#FolderListDropDown"));
     }
});

最快的方法是:

 $.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插入时,都将所有内容包装在一个元素中。

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

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

我读过使用文档片段是高性能的,因为它避免了每次插入DOM元素时页面回流,它也被所有浏览器(甚至ie6)很好地支持。

var fragment = document.createDocumentFragment(); 美元。Each (result, function() { 片段。列表末尾($(“<选项/ >”).val (this.ImageFolderID)。text (this.Name) [0]); }); $(" #选项”).append(片段);

我第一次读到这个是在CodeSchool的JavaScript最佳实践课程中。

这里是不同方法的比较,感谢作者。

或者:

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