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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/815103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:51:36  来源:igfitidea点击:

jQuery: Best practice to populate drop down?

jqueryselect

提问by Jeff Putz

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:

我一直看到发布的示例似乎不是最理想的,因为它涉及连接字符串,这似乎不是 jQuery。它通常看起来像这样:

$.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?

有没有更好的办法?

回答by Jeff Putz

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

Andreas Grech 非常接近......它实际上是this(注意引用this而不是循环中的项目):

var $dropdown = $("#dropdown");
$.each(result, function() {
    $dropdown.append($("<option />").val(this.ImageFolderID).text(this.Name));
});

回答by Andreas Grech

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

What I'm doing above is creating a new <option>element and adding it to the optionslist (assuming optionsis the ID of a drop down element.

我在上面做的是创建一个新<option>元素并将其添加到options列表中(假设options是下拉元素的 ID。

PS My javascript is a bit rusty so the syntax may not be perfect

PS我的javascript有点生疏所以语法可能不完美

回答by Shog9

Sure - make optionsan array of strings and use .join('')rather than +=every time through the loop. Slight performance bump when dealing with large numbers of options...

当然 - 制作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(''));
});

Yes. I'm still working with strings the whole time. Believe it or not, that's the fastest way to build a DOM fragment... Now, if you have only a few options, it won't really matter - use the technique Dreas demonstratesif you like the style. But bear in mind, you're invoking the browser's internal HTML parser i*2times, rather than just once, and modifying the DOM each time through the loop... with a sufficient number of options. you'll end up paying for it, especially on older browsers.

是的。我一直都在使用字符串。信不信由你,这是构建 DOM 片段的最快方法……现在,如果您只有几个选项,那其实并不重要 -如果您喜欢这种样式,请使用Dreas 演示的技术。但请记住,您要调用浏览器的内部 HTML 解析器i*2次数,而不是一次,并且每次都通过循环修改 DOM ......有足够多的选项。您最终会为此付出代价,尤其是在较旧的浏览器上。

Note:As Justice points out, this will fall apart if ImageFolderIDand Nameare not encoded properly...

注:正如法官指出,这也就土崩瓦解了,如果ImageFolderIDName正确编码...

回答by xinthink

Or maybe:

或者可能:

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

回答by Ricibald

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 linkis the fastest way because you wrap everything in a single element when doing any kind of DOM insertion.

根据此链接是最快的方法,因为在进行任何类型的 DOM 插入时,您将所有内容都包装在一个元素中。

回答by binshi

I found this to be working from jquery site

我发现这是从 jquery 站点工作的

$.getJSON( "/Admin/GetFolderList/", function( data ) {
  var options = $("#dropdownID");
  $.each( data, function(key, val) {
    options.append(new Option(key, val));
  });
});

回答by Israel Perales

Other approach with ES6

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

回答by Dapeng Li

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

我读过使用文档片段是高效的,因为它避免了每次插入 DOM 元素时的页面重排,所有浏览器(甚至 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.

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

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

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

回答by sunil

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

回答by Brian Yarger

I use the selectboxesjquery plugin. It turns your example into:

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

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