我经常看到的示例似乎不是最优的,因为它涉及到连接字符串,这似乎不是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');
        }
    });
});

});在这里输入代码

其他回答

这是我做的一个关于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');
        }
    });
});

});在这里输入代码

确定-使选项为字符串数组,并使用.join(")而不是+=每次通过循环。在处理大量选项时,性能会有轻微的提升……

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

是的。我一直都在用绳子。信不信由你,这是构建DOM片段的最快方法……现在,如果你只有几个选择,那也没关系——如果你喜欢这种风格,可以使用Dreas演示的技巧。但是请记住,您要调用浏览器的内部HTML解析器i*2次,而不是只调用一次,并且每次都要通过循环修改DOM……有足够多的选择。您最终将为此付出代价,尤其是在旧的浏览器上。

注意:正如Justice指出的,如果ImageFolderID和Name没有正确编码,这将会崩溃……

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

$('#idofselect').ajaxAddOption('/Admin/GetFolderList/', {}, false);
$.get(str, function(data){ 
            var sary=data.split('|');
            document.getElementById("select1").options.length = 0;
            document.getElementById("select1").options[0] = new Option('Select a State');
            for(i=0;i<sary.length-1;i++){
                document.getElementById("select1").options[i+1] = new Option(sary[i]);
                document.getElementById("select1").options[i+1].value = sary[i];
            }
            });

下面是填充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"));
     }
});