如果用户输入非数字值,我想添加一个将vticketqty设置为0的函数。我已经尝试过一些东西,但是如果我添加了这个功能,我的代码就无法正常工作,所以我明显做错了。
这是我正在使用的功能:
function NaN(){
if (isNaN(TicketQty)) TicketQty = 0;
} else {
return TicketQty
}
我不确定它是否正确,但我并不完全确定该功能应放在代码中的哪个位置。这是我的javascript代码。任何帮助将不胜感激。
var vTicketType;
var vTicketQty;
var vTicketPrice;
function calcTotal() {
vTicketType = prompt("Enter Ticket Type").toUpperCase();
document.write("<br>");
vTicketQty = prompt("Enter No. of Tickets");
calcPrice();
vTicketQty = parseInt(vTicketQty);
document.write("<br>");
document.write("Type of Ticket:" + vTicketType);
document.write("<br>");
document.write("Number of Tickets:" + vTicketQty);
document.write("<br>");
var vTotalPayment =(vTicketPrice) * (vTicketQty);
if (vTotalPayment >0) {
document.write("Total Payment is: $" + vTotalPayment);
vTicketPrice = parseInt(vTicketPrice);
} else {
document.write("INVALID")
}
}
function calcPrice(){
if (vTicketType == 'A') {
vTicketPrice = 50;
} else if (vTicketType == 'B') {
vTicketPrice = 30;
} else if (vTicketType == 'C'){
vTicketPrice = 10;
}
else {
vTicketPrice = -1;
}
}
答案 0 :(得分:0)
而不是:
document.write("<br>"); while (isNaN(vTicketQty)) { vTicketQty = prompt("Enter No. of Tickets"); calcPrice(); vTicketQty = parseInt(vTicketQty); if (isNaN(vTicketQty)) { alert("Quantity must be a number"); } } document.write("<br>");
试试这个。
document.write("<br>");
vTicketQty = prompt("Enter No. of Tickets");
calcPrice();
vTicketQty = parseInt(vTicketQty);
if (isNaN(vTicketQty)) {
vTicketQty = 0;
}
document.write("<br>");
编辑 - 根据要求。
document.write("<br>");
calcPrice();
vTicketQty = getQty();
document.write("<br>");
function getQty() {
qty = parseInt(prompt("Enter No. of Tickets"));
if (isNaN(qty)) {
return 0;
}
return qty;
}
已编辑 - 更多功能
<强> 1)强>
document.write("<br>");
vTicketQty = prompt("Enter No. of Tickets");
calcPrice();
vTicketQty = checkNaN(parseInt(vTicketQty));
document.write("<br>");
function checkNaN(qty) {
if (isNaN(qty)) {
return 0;
}
return qty;
}
<强> 2)强>
atomic