我的代码中有错误。
目标是,如果用户购买超过250欧元的足够球衣,我必须将其后的所有内容折扣为15%。
我的代码的第一部分工作(如果成本< = 250),上面的任何内容都给我一个(NaN)。
我的代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>
Q1 - Jerseys
</title>
<style type="text/css">
</style>
<script>
"use strict";
function processOrder()
{
//Calculations for Order
var type = document.getElementById("getType").value;
var number = parseInt(document.getElementById("getNumber").value);
var cost;
var PER_FIVE = parseFloat(0.15);
var overPrice = cost - 250;
//Logo Variables
var logo = document.getElementById("getLogo").value || "N";
var logoCost = 1.50;
//Empty Variables for Returned Values
var outputText;
//Polo Shirt Case
if (type === "Polo" && logo === "Y")
{
cost = (number * (22.50 + logoCost));
} else if (type === "Polo" && logo === "N") {
cost = parseFloat(number * 22.50);
}//End Polo
//Short Sleeve Case
if (type === "Short" && logo === "Y") {
cost = (number * (22.50 + logoCost));
} else if (type === "Short" && logo === "N") {
cost = number * 25.50;
}//End Short
//Long Sleeve Case
if (type === "Long" && logo === "Y") {
cost = (number * (22.50 + logoCost));
} else if (type === "Long" && logo === "N") {
cost = number * 28.50;
}//End Long
//Output To "results" Text Area
if (cost <= 250) {
outputText = "The cost of your jerseys is €" + cost;
document.getElementById("results").value = outputText;
} else if (cost > 250) {
outputText = "The cost of your jerseys is €" + (250 + (overPrice - (overPrice * PER_FIVE)));
document.getElementById("results").value = outputText;
}//End If
}//End Function
</script>
</head>
<body>
Please Enter details of your jersey order:
<br> <br>
Type of jersey (Polo, Short,Long):
<input id="getType" />
<br> <br>
Number of Jerseys:
<input id="getNumber" />
<br> <br>
Add A Logo:
<input id="getLogo" maxlength="1"/> Type: "Y" or "N".
<br> <br>
<button onclick="processOrder()" >Click to see results below</button>
<br> <br>
Results:
<br>
<textarea id="results" rows="4" cols="50" readonly >
</textarea>
</body>
</html>
答案 0 :(得分:0)
您在确定overPrice
之前指定了cost
:
var overPrice = cost - 250;
此时cost
为undefined
,undefined - 250
正在为您提供NaN
。
变量不是动态的 - 更新cost
不会自动更新overPrice
- 您需要在知道cost
的值后设置它。在else if
块内是合适的,因为在其他地方不需要它:
//Output To "results" Text Area
if (cost <= 250) {
outputText = "The cost of your jerseys is €" + cost;
document.getElementById("results").value = outputText;
} else if (cost > 250) {
var overPrice = cost - 250;
outputText = "The cost of your jerseys is €" + (250 + (overPrice - (overPrice * PER_FIVE)));
document.getElementById("results").value = outputText;
}//End If
另外,您在使用parseInt
时未指定radix参数。 It's recommended始终指定它以避免潜在问题:
var number = parseInt(document.getElementById("getNumber").value, 10);