jQuery: Best practice to populate drop down?

2019-01-01 08:07发布

The example I see posted all of the time seems like it's suboptimal, because it involves concatenating strings, which seems so not jQuery. It usually looks like this:

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

Is there a better way?

标签: jquery select
15条回答
若你有天会懂
2楼-- · 2019-01-01 08:15

I found this to be working from jquery site

$.getJSON( "/Admin/GetFolderList/", function( data ) {
  var options = $("#dropdownID");
  $.each( data, function(key, val) {
    options.append(new Option(key, val));
  });
});
查看更多
若你有天会懂
3楼-- · 2019-01-01 08:18

I've read that using document fragments is performant because it avoids page reflow upon each insertion of DOM element, it's also well supported by all browsers (even IE 6).

var fragment = document.createDocumentFragment();

$.each(result, function() {
  fragment.appendChild($("<option />").val(this.ImageFolderID).text(this.Name)[0]);
});

$("#options").append(fragment);

I first read about this in CodeSchool's JavaScript Best Practices course.

Here's a comparison of different approaches, thanks go to the author.

查看更多
皆成旧梦
4楼-- · 2019-01-01 08:20

Or maybe:

var options = $("#options");
$.each(data, function() {
    options.append(new Option(this.text, this.value));
});
查看更多
栀子花@的思念
5楼-- · 2019-01-01 08:20

I use the selectboxes jquery plugin. It turns your example into:

$('#idofselect').ajaxAddOption('/Admin/GetFolderList/', {}, false);
查看更多
浪荡孟婆
6楼-- · 2019-01-01 08:21

Andreas Grech was pretty close... it's actually this (note the reference to this instead of the item in the loop):

var $dropdown = $("#dropdown");
$.each(result, function() {
    $dropdown.append($("<option />").val(this.ImageFolderID).text(this.Name));
});
查看更多
查无此人
7楼-- · 2019-01-01 08:21

The fastest way is this:

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

According to this link is the fastest way because you wrap everything in a single element when doing any kind of DOM insertion.

查看更多
登录 后发表回答