我正在从事银行 ATM 项目。用户可以输入一个值来存款或取款。单击时,余额会增加,将输入值添加到初始余额中。使用 DOM 在屏幕上更改信息。所有变量都是数字。我无法将输入值添加到现有值。每次单击时,值都会重置。
我希望能够减少 onClick 余额或增加 onClick 余额。下面是我写的添加到余额中的代码。
在html中
<div class="container">
<div class="account">
<div class="account-name">Checking Account</div>
<div class="balance">Checking Account Balance:</div>
<p id="demo">1000</p>
<input type="number" id="myNumber" value="0">
<div><button id="checking-deposit-btn" class="deposit-btn">Deposit</button></div>
<button id="checking-withdraw-btn" class="withdrawal-btn">Withdrawal </button>
<div id="checking-error" >Checking Error: You have insufficient funds </div>
</div>type here
在javascript文件中
checkingAccountDepositBtn.addEventListener("click", depositFunction);
checkingAccountWithdrawalBtn.addEventListener("click", onRedButtonClick);
function depositFunction() {
let balanceValue = parseInt(document.getElementById("myNumber").value);
console.log(balanceValue)
let balance =1000
balance += balanceValue;
document.getElementById("demo").innerHTML = balance;
console.log(balance)
}
如果用户输入 100,我希望将其添加到余额中。如果用户输入 200,它应该添加到总数中。相反,它只是重置 balance 变量的值。我没有为这个项目使用本地存储。
您正在修改的余额变量仅在您调用函数以添加或减去余额时存在,因为它是在函数内声明的。这意味着您在该函数之外所做的任何事情,您将无法访问该变量,因为它仅在该函数的范围内(有关范围的更多信息here)。
您应该将代码重构为以下内容以获得所需的行为:
checkingAccountDepositBtn.addEventListener("click", depositFunction);
checkingAccountWithdrawalBtn.addEventListener("click", onRedButtonClick);
let balance =1000
function depositFunction() {
let balanceValue = parseInt(document.getElementById("myNumber").value);
console.log(balanceValue)
balance += balanceValue;
document.getElementById("demo").innerHTML = balance;
console.log(balance)
}
您需要将balance变量放在函数之外。否则,每次运行该函数时,balance 将重置为 1000 + 您添加的 value。
您将余额存储在函数内,它会覆盖已经存在的余额。您可以将余额存储在函数之外并使用函数更新它:
let balance = 1000; // store initial balance outside of function
function depositFunction() {
// rest of the code
}