使用从数据库返回的数据动态填充下拉列表 [英] Populating a dropdown dynamically with data returned from database

查看:86
本文介绍了使用从数据库返回的数据动态填充下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用从数据库返回的数据填充下拉菜单。
我的HTML是:

Im trying to populate a dropdown menu with the data returned from database. my HTML is:

 <select class="Input"></select>       

一旦我查询我的数据库,我试图将数据附加到下拉列表。

Once I query my db, Im trying to append the data to the drop down.

$(".Input").append(data[0].abc);

这里data [0] .abc指的是数组的第一个值。 abc是要返回的值的字段名称。如果该特定字段名称的值不止一个,我计划有一个for循环,它将循环遍历整个数组并附加每个值并将其添加到下拉列表中。我得到了值,但似乎无法将它们添加到下拉列表中。如果我的思考过程错误,请纠正我。
有人能指出我正确的方向吗?
谢谢。

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.

推荐答案

为了澄清@ Caner的答案,到目前为止 WAY 更快地添加到一个字符串,然后只将其附加到下拉列表一次。我不能告诉你我有多少次看到这件事。我没有时间表,但相信我。

To clarify on top of @Caner's answer, it is by far WAY faster 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.

var options = '';
$.each(data, function(index, value) {
    options += '<option value="' + value.abc + '" text="' + value.abc + '" />';
});

$('.Input').append(options);

这里的解释非常好:哪个更好:字符串html生成或jquery DOM元素创建?

这篇关于使用从数据库返回的数据动态填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆