【发布时间】:2011-08-15 02:58:20
【问题描述】:
这对某人来说应该是一个灌篮。我是一个完全的 Javascript 新手,以至于我很惊讶我能走到这一步。如此之多,以至于当您查看我的代码时,您很可能会立即看到明显的问题并嘲笑我,因为此时我在盲目地猜测语法。请查看下面的违规代码并享受笑声。我等着。
好的,所以我正在尝试制作一个简单的计算器,它显示每月购买公共汽车通行证而不是支付现金所节省的费用。我试图根据选择菜单中选择的区域显示不同的答案。当我简单地列出 if 语句之外的变量时,每个 if 语句中的公式确实有效(因此我前面提到的惊奇),在一系列警报框中显示每个答案,但我只想显示适用的答案,并且清楚我的语法完全不正常。
我很荣幸能接受这方面的教育,当然要记住我的 JS 技能还不够初级。非常感谢。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Cost Savings Calculator</title>
<script language="JavaScript">
<!-- Begin CE MP Savings Calc script
function doMath3() {
var one = eval(document.theForm3.elements[0].value)
var two = eval(document.theForm3.elements[1].value)
var three = eval(document.theForm3.elements[3].value)
if(document.theForm3.elements[3].value = "z4"){
var prodZ4 = (((one * two) * 4.25) *12) - 1680
alert("Your yearly savings if you buy a Commuter Express Zone 4 monthly pass is $" + prodZ4 + ".")
}
if(document.theForm3.elements[3].value = "z3"){
var prodZ3 = (((one * two) * 3.75) *12) - 1488
alert("Your yearly savings if you buy a Commuter Express Zone 3 monthly pass is $" + prodZ3 + ".")
}
if(document.theForm3.elements[3].value = "z2"){
var prodZ2 = (((one * two) * 3) *12) - 1200
alert("Your yearly savings if you buy a Commuter Express Zone 2 monthly pass is $" + prodZ2 + ".")
}
if(document.theForm3.elements[3].value = "z1"){
var prodZ1 = (((one * two) * 2.5) *12) - 960
alert("Your yearly savings if you buy a Commuter Express Zone 1 monthly pass is $" + prodZ1 + ".")
}
if(document.theForm3.elements[3].value = "Base"){
var prodBase = (((one * two) * 1.5) *12) - 684
alert("Your yearly savings if you buy a Commuter Express Base monthly pass is $" + prodBase + ".")
}
}
// End CE MP Savings Calc script -->
</script>
</head>
<body>
<form name="theForm3">
Days you commute monthly:
<input type="text">
Daily trips on Commuter Express:
<input type="text">
Choose Zone: <select name="zone">
<option value="Base">Base</option>
<option value="z1">Zone 1</option>
<option value="z2">Zone 2</option>
<option value="z3">Zone 3</option>
<option value="z4">Zone 4</option>
</select>
<input type="button" value="Show result" onclick="doMath3()">
</form>
</body>
</html>
【问题讨论】:
-
eval 是邪恶的。你不需要在这里使用它。使用 parseInt(value, 10) 代替(或 parseFloat)。
-
three = eval(document.theForm3.elements[3])这个至少应该改成...elements[2]
标签: javascript select menu calculator