javascript 使用从数据库返回的数据动态填充下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28330970/
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
Populating a dropdown dynamically with data returned from database
提问by pal
Im trying to populate a dropdown menu with the data returned from database. my HTML is:
我试图用从数据库返回的数据填充下拉菜单。我的 HTML 是:
<select class="Input"></select>
Once I query my db, Im trying to append the data to the drop down.
一旦我查询了我的数据库,我就会尝试将数据附加到下拉列表中。
$(".Input").append(data[0].abc);
Here "data[0].abc" refers to the first value of the array. abc is the field name of the value being returned. In case of more than one values for that particular field name, I plan to have a for loop which will loop through the entire array and append each value and add it to the drop down. I get the values but cant seem to add them to the drop down. Please correct me if my thought process is wrong. Can someone point me in the right direction? Thank you.
这里“data[0].abc”指的是数组的第一个值。abc 是返回值的字段名称。如果该特定字段名称有多个值,我计划有一个 for 循环,它将遍历整个数组并附加每个值并将其添加到下拉列表中。我得到了值,但似乎无法将它们添加到下拉列表中。如果我的思考过程有误,请纠正我。有人可以指出我正确的方向吗?谢谢你。
采纳答案by Rob Scott
To clarify on top of @Caner's answer, it is by far WAYfaster to add those to a string, and then append it to the dropdown only once. I cannot tell you how many times I see this being done. I don't have a timeline of it, but trust me.
要澄清的@蚕儿的回答上面,它是迄今为止WAY更快那些添加到字符串,然后将其追加到下拉只有一次。我无法告诉你我看到多少次这样做了。我没有时间表,但相信我。
var options = '';
$.each(data, function(index, value) {
options += '<option value="' + value.abc + '" text="' + value.abc + '" />';
});
$('.Input').append(options);
Pretty good explanation here: Which is better: string html generation or jquery DOM element creation?
回答by Caner Akdeniz
Try this:
试试这个:
$('.Input').append('<option>' + data[0].abc + '</option');