【发布时间】:2020-12-24 16:11:36
【问题描述】:
我想在选择选项上循环来自 JSON 文件的值, 这是我的 JSON 文件外观
[{
"vehicle": "car1",
"type": [
{"name" : "BMW",
"details" : [{
"color" : "red",
"price" : "50000"
},
{
"color" : "blue",
"price" : "51000"
}]}
]},
{
"vehicle": "car2",
"type": [
{"name" : "Lambo",
"details" : [{
"color" : "green",
"price" : "150000"
},
{
"color" : "yellow",
"price" : "151000"
}]}
]}
]
我想填充 2 选择中的值, 这是我使用循环的代码
for (i = 0; i < data.length; i++) {
select1.insertAdjacentHTML('beforeend', `
<option>${data[i].vehicle}</option>
`)
for (j = 0; j < data[i].type.length; j++) {
for (k = 0; k < data[i].type[j].details.length; k++) {
select2.insertAdjacentHTML('beforeend', `
<option">${data[j].type[j].details[k].color}</option>
`)
}
}
}
我的目标是我的第一个选择选项:
- 汽车1
- 汽车2
第二个选择选项是:
- 红/绿
- 蓝色/黄色
基于第一个选择,所以如果我选择汽车 1 并且在选择 2 中只显示红色和蓝色, 在我的代码中,select2 显示了 4 项,
谁能帮我解决这个问题?谢谢
var json_obj = [{
"vehicle": "car1",
"type": [
{"name" : "BMW",
"details" : [{
"color" : "red",
"price" : "50000"
},
{
"color" : "blue",
"price" : "51000"
}]}
]},
{
"vehicle": "car2",
"type": [
{"name" : "Lambo",
"details" : [{
"color" : "green",
"price" : "150000"
},
{
"color" : "yellow",
"price" : "151000"
}]}
]}
];
function apply_change(data) {
var select1 = document.getElementById('select1');
var select2 = document.getElementById('select2');
for (i = 0; i < data.length; i++) {
select1.insertAdjacentHTML('beforeend', `
<option>${data[i].vehicle}</option>
`)
for (j = 0; j < data[i].type.length; j++) {
for (k = 0; k < data[i].type[j].details.length; k++) {
select2.insertAdjacentHTML('beforeend', `
<option">${data[j].type[j].details[k].color}</option>
`)
}
}
}
}
apply_change(json_obj);
select 1: <select id="select1"></select>
select 2: <select id="select2"></select>
【问题讨论】:
-
只有在用户改变了select1的值后才设置select2的内容(在select1上添加一个事件监听器)。
-
取一个颜色数组;在选择汽车选项时初始化此数组。通过在特定条件下迭代您的对象,将颜色推送到此数组。
标签: javascript json ajax