当我点击我的按钮时,我正试图在JavaScript中显示价格,但它只是向我显示我的警报。谁能告诉我哪里出错了?这是我的功能:
function prompttotalCost() {
var totalCost;
var costPerCD;
var numCDs;
numCDS = prompt("Enter the number of Melanie's CDs you want to buy");
if (numCDS > 0) {
totalCost = totalCost + (costPerCD * numCDs);
alert("totalCost+(costPerCD*numCDs)");
totalCost = 0;
costPerCD = 5;
numCDs = 0;
} else {
alert("0 is NOT a valid purchase quantity. Please press 'OK' and try again");
} // end if
} // end function prompttotalCost
答案 0 :(得分:1)
问题是numCDs
是一个字符串,而不是一个数字,因为prompt
返回一个字符串。你可以,例如使用parseInt
将其转换为数字:
numCDS = parseInt(prompt("Enter the number of Melanie's CDs you want to buy"));
接下来的事情:在使用它之前,你没有给totalCost
赋值 - 这很糟糕。将var totalCost;
更改为var totalCost = 0;
或将totalCost = totalCost + (costPerCD * numCDs);
更改为totalCost = (costPerCD * numCDs);
。
此外,在alert
调用中,您要将要执行的内容作为代码放入字符串中。变化
alert("totalCost+(costPerCD*numCDs)");
这样的事情:
alert("totalCost is "+totalCost);