javascript 使用 jquery 或 JS 填充 Html.DropDownList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10077596/
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-10-26 08:36:20  来源:igfitidea点击:

Populate Html.DropDownList with jquery or JS

javascriptjquery

提问by user1322207

Here is what I have:

这是我所拥有的:

for (i = 0; i < data.length; i++) {
                $("#myDropDownLisTId").find('tbody')  
                .append($('<option>').attr('value', data[i].id).attr('name', data[i].name)
                );               
            }

But the dropdown list always remains the same. Why is this not working? the data variable has beautiful values. Also, I would like before the for loop to empty the dropdown list/ How to do it?

但下拉列表始终保持不变。为什么这不起作用?数据变量具有漂亮的值。另外,我想在 for 循环之前清空下拉列表/如何做?

Here is my drop down list in the view:

这是我在视图中的下拉列表:

<%= Html.DropDownList("myDropDownLisTId")%>

回答by idrumgood

Though the other answers will accomplish what you wish to do, I would recommend writing your option HTML to a string variable and appending it after the loop has finished, rather than appending within the loop. This can have some noticeable performance advantages when your list gets longer. Using .html()will also take care of emptying the list each time.

尽管其他答案可以完成您想要做的事情,但我建议将您的选项 HTML 写入字符串变量并在循环完成后附加它,而不是在循环内附加。当您的列表变长时,这可能具有一些明显的性能优势。Using.html()也将负责每次清空列表。

        var tempList = '';
        for (i = 0; i < data.length; i++) {  
            tempList += '<option value="' + data[i].id + '" name="' + data[i].name +'">' + data[i].text + '</option>';            
        }
        $("#myDropDownLisTId").html(tempList);

回答by Shyju

Try this.

试试这个。

$.each(data, function() {
   $("#myDropDownLisTId").append($("<option />").val(this.id).text(this.Text));
 });

Check my this answerfor more details about how to get data from an MVC action to load the dropdown list

有关如何从 MVC 操作获取数据以加载下拉列表的更多详细信息,请查看我的此答案

EDIT:As per the comment to remove existing data

编辑:根据删除现有数据的评论

$("#myDropDownLisTId").empty()
$.each(data, function() {
   $("#myDropDownLisTId").append($("<option />").val(this.id).text(this.Text));
 });

EDIT 2:? Idrumsgood's answer has a very good point. Instead of calling the append method everytime inside the loop, just keep the value inside a variable and call the html method only once.

编辑2: Idrumsgood的回答有一个很好的观点。无需每次在循环内调用 append 方法,只需将值保存在变量中并仅调用一次 html 方法。

http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly

http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly

var items=""
$.each(data, function() {
   items+="<option value='" + this.id + "'>" + this.Text + "</option>";
 });
$("#myDropDownLisTId").html(items);

回答by Brandon Boone

This seems to work: http://jsfiddle.net/ykFJd/2/

这似乎有效:http: //jsfiddle.net/ykFJd/2/

JS

JS

var data = [
    {id:'0', name:'test 0'},  
    {id:'1', name:'test 1'},
    {id:'2', name:'test 2'},
    {id:'3', name:'test 3'},
    {id:'4', name:'test 4'},    
];


for (var i = 0; i < data.length; i++) {
    $("#myDropDownLisTId").append(
        $('<option />', {
            'value': data[i].id,
            'name': data[i].name,
            'text': data[i].name
        })
    );               
}?

回答by Walter Stabosz

I wrote a nice function for binding a js hash to a select lists. See my answer at Best way to populate select list with JQuery / Json?

我编写了一个很好的函数,用于将 js 哈希绑定到选择列表。请参阅我在使用 JQuery/Json 填充选择列表的最佳方式中的回答

Example usage:

用法示例:

// you can easily pass in response.d from an AJAX call if it's JSON formatted
var users = [ {id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Cindy'} ]
setSelectOptions($('#selectList'), users, 'id', 'name');