我正在尝试使用按钮创建购买系统

时间:2017-10-24 07:44:47

标签: javascript html

我正在尝试创建一个系统,显示您拥有的金额,显示您购买的商品的成本,有一个按钮,当点击时带走了您的金额,并增加了它的数量取消每次点击,但按钮不起作用。

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="buyA.js">
    </script>
    <title>Test Page</title>
</head>
<body>
    <p id="money">
        <script>
        document.getElementById("money").innerHTML = "Money: " + money;
        </script>
    </p>
    <p id="cost">
        <script>
        document.getElementById("cost").innerHTML = "Cost: " + buyA;
        </script>
    </p>
    <input id="Purchase" type="button" value="Purchase" onclick="BuyA();"/>
</body>
</html>

var money = 1000;
var buyA = 500;

function BuyA() {
    if (money >= buyA) {
        money - buyA;
        buyA + 250;
    }
    else {
        window.alert("Not Enough Money")
    }
}

1 个答案:

答案 0 :(得分:1)

您将脚本放在错误的位置。此外,您在分配值时遇到了错误(moneybuyA)。

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="buyA.js">
    </script>
    <title>Test Page</title>
    
    <!-- Put your scripts here -->
    <script>
    var money = 1000;
    var buyA = 500;

    function BuyA() {
        if (money >= buyA) {
            // deduct the money
            // money - buyA;
            money = money - buyA;
            
            // increase the price
            // buyA + 250;
            buyA = buyA + 250;
            
            // update the values
            document.getElementById("money").innerHTML = "Money: " + money;
            document.getElementById("cost").innerHTML = "Cost: " + buyA;
        }
        else {
            window.alert("Not Enough Money")
        }
    }
    </script>
</head>
<body>
    <p id="money"></p>
    <p id="cost"></p>
    <script>
    // update the values
    document.getElementById("money").innerHTML = "Money: " + money;
    document.getElementById("cost").innerHTML = "Cost: " + buyA;
    </script>
    <input id="Purchase" type="button" value="Purchase" onclick="BuyA();"/>
</body>
</html>