我正在尝试制作简单的应用,我有以下想法。我有两个输入字段,用户可以选择城市,我也有JSON,我想从中获得结果。现在我想要的是取决于用户选择哪个城市他得到不同的结果。这是我的对象(JSON):
var cities = {
"newyork": {
"newyork": 0,
"washington": 50,
"sacramento": 100,
"miami": 150
},
"washington": {
"washington": 0,
"newyork": 50,
"sacramento": 100,
"miami": 150
}
};
这是我的HTML:
<form>
<select id="firstInput" onchange="calculatePrice()">
<option value="newyork">newyork</option>
<option value="washington">washington</option>
<option value="sacramento">sacramento</option>
<option value="miami">miami</option>
</select>
<select id="secondInput" onchange="calculatePrice()">
<option value="newyork">newyork</option>
<option value="washington">washington</option>
<option value="sacramento">sacramento</option>
<option value="miami">miami</option>
</select>
</form>
<div id="output">Output: 500</div>
我想要实现的事情的例子:用户在第一个输入中选择纽约,在第二个输入中选择萨克拉门托。输出更改为50.如您所见,我想从JS中加载JSON或对象中的数据。
这是我的JS:
function calculatePrice() {
var x = document.getElementById("firstInput").value;
console.log(x);
var y = document.getElementById("secondInput").value;
console.log(y);
console.log(cities.x.y);
document.getElementById("output").innerHTML = "Output: " + cities.x.y;
}
但是使用此代码我收到以下错误:
Uncaught TypeError: Cannot read property 'y' of undefined
这很令人困惑,因为当我在console.log(y)时它看起来工作得很好
谁能帮我这个 ?
这是JSBin,所以你可以更好看:
https://jsbin.com/laluzawuda/edit?html,js,console,output
答案 0 :(得分:2)
cities.x.y
应为cities[x][y]
。 cities.x.y
在x
中查找名为cities
的属性,它不会将变量的值用作属性名称。见http://stackoverflow.com/questions/4244896/dynamically-access-object-property。
function calculatePrice() {
var x = document.getElementById("firstInput").value;
console.log(x);
var y = document.getElementById("secondInput").value;
console.log(y);
if (cities[x] && cities[x][y]) {
console.log(cities[x][y]);
document.getElementById("output").innerHTML = "Output: " + cities[x][y];
} else {
console.log("No flights from " + x + " to " + y);
}
}
var cities = {
"newyork": {
"newyork": 0,
"washington": 50,
"sacramento": 100,
"miami": 150
},
"washington": {
"washington": 0,
"newyork": 50,
"sacramento": 100,
"miami": 150
}
};
&#13;
<form>
<select id="firstInput" onchange="calculatePrice()">
<option value="newyork">newyork</option>
<option value="washington">washington</option>
<option value="sacramento">sacramento</option>
<option value="miami">miami</option>
</select>
<select id="secondInput" onchange="calculatePrice()">
<option value="newyork">newyork</option>
<option value="washington">washington</option>
<option value="sacramento">sacramento</option>
<option value="miami">miami</option>
</select>
</form>
<div id="output">Output: 500</div>
&#13;