代码之家  ›  专栏  ›  技术社区  ›  Jeff Putz

jQuery:填充下拉列表的最佳实践?

  •  250
  • Jeff Putz  · 技术社区  · 17 年前

    我一直看到的这个例子似乎不太理想,因为它涉及到串接字符串,而串接字符串似乎不是jQuery。通常是这样的:

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

    有更好的办法吗?

    15 回复  |  直到 17 年前
        1
  •  483
  •   João Pimentel Ferreira    8 年前

    安德烈亚斯·格雷奇非常接近。。。实际上是 this 而不是循环中的项):

    var $dropdown = $("#dropdown");
    $.each(result, function() {
        $dropdown.append($("<option />").val(this.ImageFolderID).text(this.Name));
    });
    
        2
  •  72
  •   Andreas Grech    17 年前
    $.getJSON("/Admin/GetFolderList/", function(result) {
        var options = $("#options");
        //don't forget error handling!
        $.each(result, function(item) {
            options.append($("<option />").val(item.ImageFolderID).text(item.Name));
        });
    });
    

    我在上面所做的是创建一个新的 <option> options 名单(假设) 选择权

        3
  •  42
  •   Community Mohan Dere    9 年前

    确定 options .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 demonstrates 如果你喜欢这个款式。但请记住,您正在调用浏览器的内部HTML解析器 i*2

    正如正义所指出的,如果 ImageFolderID Name 不是 encoded properly ...

        4
  •  25
  •   xinthink    10 年前

    var options = $("#options");
    $.each(data, function() {
        options.append(new Option(this.text, this.value));
    });
    
        5
  •  20
  •   Ricibald    17 年前

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

    根据 this link 是最快的方法,因为在执行任何类型的DOM插入时,都将所有内容包装在单个元素中。

        6
  •  12
  •   binshi    10 年前

    $.getJSON( "/Admin/GetFolderList/", function( data ) {
      var options = $("#dropdownID");
      $.each( data, function(key, val) {
        options.append(new Option(key, val));
      });
    });
    
        7
  •  5
  •   Dapeng Li    10 年前

    我已经读过了 document fragments 因为它避免了每次插入DOM元素时的页面回流,所以它也得到了所有浏览器(甚至IE 6)的良好支持。

    var fragment = document.createDocumentFragment();
    
    $.each(result, function() {
      fragment.appendChild($("<option />").val(this.ImageFolderID).text(this.Name)[0]);
    });
    
    $("#options").append(fragment);

    我第一次读到这篇文章是在 CodeSchool's JavaScript Best Practices course .

    这里有一个 comparison of different approaches

        8
  •  5
  •   Israel Perales    9 年前

    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));
        });
      })
    
        9
  •  3
  •   Pablo Rocha Villagra    10 年前

    我通常使用函数,而不是每次编写所有代码。

        $("#action_selector").change(function () {
    
            ajaxObj = $.ajax({
                url: 'YourURL',
                type: 'POST', // You can use GET
                data: 'parameter1=value1',
                dataType: "json",
                context: this,                
                success: function (data) {
                    json: data              
                },
                error: function (request) {
                    $(".return-json").html("Some error!");
                }
            });
    
            json_obj = $.parseJSON(ajaxObj.responseText);            
    
            var options = $("#selector");
            options.empty();
            options.append(new Option("-- Select --", 0));
            $.each(ajx_obj, function () {
                options.append(new Option(this.text, this.value));
            });
        });
    });
    
        10
  •  2
  •   Brian Yarger    17 年前

    我使用 selectboxes jquery插件。它将您的示例转化为:

    $('#idofselect').ajaxAddOption('/Admin/GetFolderList/', {}, false);
    
        11
  •  2
  •   sunil    14 年前
    $.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];
                }
                });
    
        12
  •  1
  •   Deenathaiyalan Shanmugam    9 年前
    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(""));
        });
    }
    
        13
  •  1
  •   Du-Lacoste    9 年前
    function generateYears() {
                        $.ajax({
                            type: "GET",
                            url: "getYears.do",
                            data: "",
                            dataType: "json",
                            contentType: "application/json",
                            success: function(msg) {
                                populateYearsToSelectBox(msg);
                            }
                        });
    }
    
    function populateYearsToSelectBox(msg) {
      var options = $("#selectYear");
    $.each(msg.dataCollecton, function(val, text) {
       options.append(
            $('<option></option>').val(text).html(text)
        );
    });
    }
    
        14
  •  1
  •   Abdelghafour Ennahid    8 年前

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

    }); enter code here

        15
  •  1
  •   tash    5 年前

    result.forEach(d=>$("#dropdown").append(new Option(d,d)))
    
        16
  •  0
  •   Elim Garak    10 年前

    function loadDropDowns(name,value)
    {
       var ddl = "#Categories";
       $(ddl).append('<option value="' + value + '">' + name + "</option>'");
    }
    
        17
  •  0
  •   Hang Yu    6 年前

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

    $.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"));
         }
    });