1

当我的按钮被点击时,我试图在 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
4

1 回答 1

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);
于 2013-03-31T15:59:12.180 回答