首页 > 解决方案 > 每次使用 onClick 事件时如何防止变量返回原始值

问题描述

您好我有以下用于 ATM 取款机的 HTML 和 javascript 代码。代码有效,但每次从用户提款后余额不会减少(从 400 美元开始)。我找不到问题所在或如何解决此问题。任何帮助,将不胜感激。

<!DOCTYPE html>
<html>

<head>
    <title>ATM</title>
    <style>
        #bank {
            text-align: center;
        }

        button {
            padding-left: 6px;
            padding-right: 6px;
        }
    </style>
    <script type="text/javascript" src="Q2.js">
    </script>
</head>

<body>
    <form id="bank">
        <h2> Question 2 </h2>
        <h5>ATM Machine</h5>
        <input type="text" id="cash" placeholder="Enter withdrawal amount" size="25">
        <button type="submit" onclick="validateAmount()" id="button">Submit</button>
    </form>
</body>

</html>

这是javascript

balance = 400.00;


function validateAmount() {
    a = document.getElementById("cash");
    amount = a.value;

    if (isNaN(amount)) {
        alert("Please enter a numeric value");
    } else {

            withdrawlAmount();
    }
}

function withdrawlAmount() {


    if (amount >= balance)
        alert("Insufficent Funds");
    else if (amount % 20 != 0)
        alert("Incorrect withdrawl amount");
    else if (amount < balance) {
        alert("Succeful transaction\nCurrent Balance: " + (balance - amount) + "$");
        balance -= amount;
    } else {
        return;
    }
}

标签: javascripthtmlloopsif-statementonclick

解决方案


您的 HTML 提交按钮将在您每次按下它时刷新页面,从而重新运行您的 javascript 并将余额重置为 400。要解决此问题,请将按钮类型从“提交”更改为“按钮”。


推荐阅读