我有一个带有2个下拉菜单输入的HTML5表单。 该表格用于确定两个公司位置之间的距离。
当前的脚本可以工作,但是效果不是很好,因为它可以在几个位置工作,但就我而言,不能在23个位置工作。
如何制作一个“交叉引用函数”来检查一长串的变量和值?
用于检查所选下拉菜单并返回值的javascript函数:
inputField
是显示与用户距离的字段。
function initCalc(inputField,select1,select2) {
select1.change(function(){
inputField.val(calculateValue(select1.val(),select2.val()));
});
select2.change(function(){
inputField.val(calculateValue(select1.val(),select2.val()));
});
}
“计算”距离:
function calculateValue(firstOp,secondOp) {
var kmCost = 0.19;
if (firstOp == "Company1" && secondOp == "Company1") { var total = 0; }
else if (firstOp == "Company1" && secondOp == "Company2") { var total = 205; }
else if (firstOp == "Company1" && secondOp == "Company3") { var total = 174; }
else if (firstOp == "Company1" && secondOp == "Company4") { var total = 3; }
else if (firstOp == "Company1" && secondOp == "Company5") { var total = 21; }
else if (firstOp == "Company1" && secondOp == "Company6") { var total = 129; }
else if (firstOp == "Company2" && secondOp == "Company1") { var total = 205; }
else if (firstOp == "Company2" && secondOp == "Company2") { var total = 0; }
else if (firstOp == "Company2" && secondOp == "Company3") { var total = 11; }
//etc...
else { var total = 0; }
var total = total * kmCost;
return total.toFixed(2);
}
在@JRK的帮助下,我提供了以下内容,但是我想我做错了什么,无法从对象中获取下拉列表的值?
function calculateValue(firstOp,secondOp) {
var kmCost = 0.19;
var myObject = {Amsterdam : {distances : {Paris : 1, NewYork : 2}},
Paris : {distances : {Amsterdam : 1, NewYork : 3}},
NewYork : {distances : {Amsterdam : 2, Paris : 3}}
};
var total = myObject.firstOp.distances.secondOp;
var total = total * kmCost;
return total.toFixed(2);
}
我知道了! 感谢this post。
function calculateValue(firstOp,secondOp) {
var kmCost = 0.19;
var myObject = {Amsterdam : {distances : {Paris : 1, NewYork : 2}},
Paris : {distances : {Amsterdam : 1, NewYork : 3}},
NewYork : {distances : {Amsterdam : 2, Paris : 3}}
};
var total = myObject[firstOp]['distances'][secondOp];
var total = total * kmCost;
return total.toFixed(2);
}
答案 0 :(得分:0)
我知道了! 感谢this post。
function calculateValue(firstOp,secondOp) {
var kmCost = 0.19;
var myObject = {Amsterdam : {distances : {Paris : 1, NewYork : 2}},
Paris : {distances : {Amsterdam : 1, NewYork : 3}},
NewYork : {distances : {Amsterdam : 2, Paris : 3}}
};
var total = myObject[firstOp]['distances'][secondOp];
var total = total * kmCost;
return total.toFixed(2);
}