我无法为输入分配特定值。例如,当用户通过TicketType提示输入字母时,我希望将该字母转换为数字。所以说他们进入了B'作为他们的TicketType,我想要' B'要转换为50所以我可以后者计算总成本。目前TotalPayment只显示NaN,我很困惑。
这是我的JavaScript代码:
function ticket() {
var TicketType;
TicketType = prompt("Please enter the type of ticket you require!");
document.write("<br>");
var TicketQty;
TicketQty = prompt("Please enter the number of tickets you require!");
TicketQty = parseInt(TicketQty);
document.write("Number of Tickets:" + TicketQty);
document.write("<br>");
var TotalPayment =(TicketPrice) * (TicketQty);
document.write("Total Payment is:" + TotalPayment);
var TicketPrice;
TicketPrice = parseInt(TicketPrice);
if (TicketType == A) {
TicketPrice == 100;
}
else if (TicketType == B) {
TicketPrice == 75;
}
else if (TicketType == C){
TicketPrice == 50;
}
else {
document.write("Invalid Ticket Type");
}
}
这是我的HTML代码:
<html>
<title>Ticket</title>
<h1>Ticket</h1>
<script src="test.js"> </script>
<script>calculate()</script>
</body>
答案 0 :(得分:0)
您的字符串比较完全错误。我正在限制我的回答,因为这是你所要求的。
if (TicketType == A) {
需要:
if (TicketType === "A") {
此外,您必须清楚分配'='与比较'=='。
整个部分应该更像这样:
if (TicketType === "A") {
TicketPrice = 100;
} else if (TicketType === "B") {
TicketPrice = 75;
} else if (TicketType === "C")
TicketPrice = 50;
else {
document.write("Invalid Ticket Type");
}
当你有一个链接的if-then-elseif
时,查看switch语句您的代码还有其他问题。 Here's a jsfiddle有一些修复和改进。
答案 1 :(得分:0)
你需要改变两件事:
1:字符串比较
if (TicketType == A)
到
if (TicketType == 'A')
2:错误分配
TicketPrice == 100
到
TicketPrice = 100
答案 2 :(得分:0)
尝试以下方法:
var TicketType;
var TicketQty;
var TicketPrice;
function calculateticket() {
TicketType = prompt("Please enter the type of ticket you require!");
document.write("<br>");
TicketQty = prompt("Please enter the number of tickets you require!");
testType();
}
calculateticket();
function testType(){
if(TicketType =='A' || TicketType == 'B' || TicketType == 'C'){
if (TicketType == 'A') {
TicketPrice = 100;
} else if (TicketType == 'B') {
TicketPrice = 75;
} else if (TicketType == 'C'){
TicketPrice = 50;
}
TicketQty = parseInt(TicketQty);
document.body.innerHTML += '<span id="text1"></span>';
document.getElementById('text1').innerHTML = 'Total Payment is: '+TicketQty;
document.write("<br>");
var TotalPayment =(TicketPrice) * (TicketQty);
document.body.innerHTML += '<span id="text2"></span>';
document.getElementById('text2').innerHTML = 'Total Payment is: '+TotalPayment;
TicketPrice = parseInt(TicketPrice);
}
else {
if(document.getElementById('text1') != null){
document.getElementById('text1').innerHTML = '';
}
if(document.getElementById('text2') != null){
document.getElementById('text2').innerHTML = '';
}
document.write("Invalid Ticket Type");
}
}
&#13;