因此,我正在努力在JSON对象中访问JSON对象(不确定是否更容易将其存储为数组),以尝试为用户选择提供更多自定义。
当我选择某种类型的苹果时,我想这样做(b),然后弹出第三个切换,我可以在重量1或2之间进行选择,它将以相同的方式填充重量字段就像我挑选另一种水果或选择一样。
Js小提琴包含所有代码,但我也会在下面发布代码。 http://jsfiddle.net/K8PcH/12/
// The JSON this is all pulled from
var json = {
"Apple": {
"A": {
"weight": 6,
"price": 3.99
},
"B": {
"weight": {
"weight1": 5,
"weight2": 12
},
"price": 4.99
}
},
"Orange": {
"1": {
"weight": 4,
"price": 4.49
},
"2": {
"weight": 5,
"price": 5.49
}
}
};
// Create the first dropdown
var dropdown1 = document.createElement("select");
// Populate the first dropdown
var option = document.createElement("option");
option.innerHTML = "Select a fruit";
option.value = "none";
dropdown1.appendChild(option);
// Add options from JSON
for (var attr in json) {
var option = document.createElement("option");
option.innerHTML = option.value = attr;
dropdown1.appendChild(option);
}
// Add the first dropdown to the page (body)
document.body.appendChild(dropdown1);
// Create the second dropdown
var dropdown2 = document.createElement("select");
var option = document.createElement("option");
option.innerHTML = "N/A";
dropdown2.appendChild(option);
// Add the second dropdown to the page (body)
document.body.appendChild(dropdown2);
// Add info field
var info = document.createElement("div");
document.body.appendChild(info);
// Function to automatically fill the weight/price fields
var auto_fill_fields = function() {
if (dropdown1.value != "none") {
var obj = json[dropdown1.value][dropdown2.value];
var weight_str = "Weight: " + obj.weight + " oz";
var price_str = "Price: $" + obj.price;
info.innerHTML = dropdown1.value + " " + dropdown2.value + " " + weight_str + " " + price_str;
} else {
info.innerHTML = "";
}
};
// Handle changing the first dropdown
dropdown1.addEventListener("change", function() {
// Remove the current options from the second dropdown
$(dropdown2).empty();
// Did they actually select a fruit?
if (this.value != "none") { // Yes
// Populate the second dropdown
for (var attr in json[this.value]) {
var option = document.createElement("option");
option.innerHTML = option.value = attr;
dropdown2.appendChild(option);
}
} else { // No
// There's nothing to choose
var option = document.createElement("option");
option.innerHTML = "N/A";
dropdown2.appendChild(option);
}
auto_fill_fields();
});
// Handle changing the second dropdown
dropdown2.addEventListener("change", auto_fill_fields);
// Fill in initial values
auto_fill_fields();