在页面加载时,您可以使用可工作的fiddle将价格索引到二维地图中。
1)我将选择的值放入查找表中,以防必须预加载它们:
var tables = {
Colour: ["Blue", "Red"],
Size: ["Small", "Medium", "Large"]
};
2) 这是您的价格表以数组形式呈现:
var array = [
{Colour: "Blue", Size: "Small", Price: 45},
{Colour: "Blue", Size: "Medium", Price: 48},
{Colour: "Blue", Size: "Large", Price: 98},
{Colour: "Red", Size: "Small", Price: 65},
{Colour: "Red", Size: "Large", Price: 31}
];
3) 初始化选择器(填充值和事件“change”):
for (var key in tables)
if (tables.hasOwnProperty(key)) {
selects[key] = form[key];
selects[key].addEventListener("change", updateSpan);
var values = tables[key];
len = values.length;
for (i = 0; i < len; i++) {
var option = document.createElement('option');
option.appendChild(document.createTextNode(values[i]));
form[key].appendChild(option);
}
}
4) 将价格表编入索引:
len = array.length;
for (i = 0; i < len; i++) {
var record = array[i];
if (typeof map[record.Colour] === 'undefined')
map[record.Colour] = {};
map[record.Colour][record.Size] = record.Price;
}
5)在选择更改时更新span函数:
function updateSpan() {
var Colour = selects.Colour.options[selects.Colour.selectedIndex].value;
var Size = selects.Size.options[selects.Size.selectedIndex].value;
if (typeof map[Colour] !== 'undefined' && typeof map[Colour][Size] !== 'undefined')
span.textContent = map[Colour][Size];
else
span.textContent = "Price not defined to Colour: " + Colour + " and Size: " + Size + ".";
}
6) 调试(在Chrome或Firefox中按F12以打开控制台视图)。
完整索引表:
console.log(map)
仅显示 'Blue' 和 'Small' 的价格:
console.log(map['Blue']['Small'])
var answer = data[1][2][3];
或answer = data[2][2][3];
。当然,您必须使用正确的数据填充这个三维数组。 - jfriend00