gpt4 book ai didi

javascript - 用 JSON 数据填充多个选择框

转载 作者:行者123 更新时间:2023-11-30 18:18:03 25 4
gpt4 key购买 nike

我有以下数据库表(虽然数据库中有更多数据,但还不是全部!):

catid   value   description
0 350 350 euro
0 500 500 euro
0 650 650 euro
1 0 No
1 1 Yes


在 PHP 和 json_encode() 的帮助下,我正在为这个表创建一个 JSON 字符串:

jQuery171024539993586950004_1349776890005([{"0":"0","catid":"0","1":"350","value":"350","2":"350 euro","description":"350 euro"},{"0":"0","catid":"0","1":"500","value":"500","2":"500 euro","description":"500 euro"},{"0":"0","catid":"0","1":"650","value":"650","2":"650 euro","description":"650 euro"},{"0":"1","catid":"1","1":"0","value":"0","2":"No","description":"No"},{"0":"1","catid":"1","1":"1","value":"1","2":"Yes","description":"Yes"}])

现在我想要的是使用 JSON 来填充选择框,就像在 HTML 中一样:

<select id="0">
<option value="350">350 euro</option>
<option value="500">500 euro</option>
<option value="650">650 euro</option>
</select>

<select id="1">
<option value="0">No</option>
<option value="1">Yes</option>
</select>

谁能帮我解决这个问题?我知道如何循环填充表格(使用 $.getJSON),但我有点受困于此。

最佳答案

此函数将遍历您发布的对象并填充菜单(给定您发布的源):

var populateSelects = function(data) {
var cat0 = $('select#0'),
cat1 = $('select#1'),
opt = $('<option />'),
newOpt = {},
cat0opts = [],
cat1opts = [];
$.each(data, function(i, obj) {
//clone the option element so as to not re-create a new one
newOpt = opt.clone();
//obj is the JavaScript object in the array, so
//dot-notation works nicely
newOpt.text(obj.description).val(obj.value);
if (obj.catid === "0") {
//push the DOM element, not the jQuery object
cat0opts.push(newOpt[0]);
} else if (obj.catid === "1") {
cat1opts.push(newOpt[0]);
}
});
//Add the array of DOM elements to their respective menus,
//clearing out any existing menu items.
cat0.empty().append(cat0opts);
cat1.empty().append(cat1opts);
};

这是它的一个 fiddle Action :http://jsfiddle.net/a5MTE/1/

一个重要的注意事项是 catid 比较...如果解析的 JSON 返回 catid 作为数字(不是字符串),您需要将比较更改为if (obj.catid === 0).

关于javascript - 用 JSON 数据填充多个选择框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12797727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com