我试图在单击按钮时以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

最佳答案

问题是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);

09-25 12:56