我正在将ATM应用程序作为学校项目进行,本质上,支票和储蓄帐户的背景颜色根据当前余额而变化。问题是,尽管它更改为红色(由于帐户默认为0),但没有更改为黄色(50美元)或绿色(100美元)
currentBalance是全局的,以保留数据。它从那里拉那个变量。 “ ID”专用于支票帐户或储蓄帐户。我可以确认颜色更改有效,因为它已从绿色(默认值)更改为红色,但是一旦开始进行实时更新就不会改变。
var currentBalance = 0
function depositMoney(id) {
// Select deposit button and add functionality
document.querySelector(`${id} .deposit`).addEventListener("click", function(event) {
// Prevent refresh page default
event.preventDefault()
// Obtain data from input box
let deposited = document.querySelector(`${id} .input`).value
// Turn data (currently string) into a number
let intDeposited = parseInt(deposited)
// Add number to current balance
currentBalance += intDeposited
// Select balance div which is where the balance will be shown
let balanceNumber = document.querySelector(`${id} .balance`)
// Show changed balance by modifying innerHTML and turning current balance into a string
balanceNumber.innerHTML = "$" + currentBalance.toString();
})
}
function backgroundColorBalance(id) {
let accountColor = document.querySelector(`${id}`)
if (currentBalance <= 25 && currentBalance >= 0) {
accountColor.style.backgroundColor = "red"
}
if (currentBalance <= 50 && currentBalance > 25) {
accountColor.style.backgroundColor = "yellow"
}
if (currentBalance > 50) {
accountColor.style.backgroundColor = "green"
}
}
// Invoke depositMoney() function for checking account
depositMoney("#checking")
// Invoke backgroundColorBalance() function for checking account
backgroundColorBalance("#checking")
<div class="header">
<div><img src="ga.png" /></div>
<div class="title">Bank of GA</div>
</div>
<div id="checking" class="account">
<h2>Checking</h2>
<div class="balance">$0</div>
<input class="input" type="text" placeholder="enter an amount" />
<input class="deposit" type="button" value="Deposit" />
<input class="withdraw" type="button" value="Withdraw" />
</div>
<div id="savings" class="account">
<h2>Savings</h2>
<div class="balance">$0</div>
<input class="input" type="text" placeholder="enter an amount" />
<input class="deposit" type="button" value="Deposit" />
<input class="withdraw" type="button" value="Withdraw" />
</div>
更改帐户余额后,您需要重置背景色。因此,将以下内容添加为事件侦听器代码的最后一行。
backgroundColorBalance(`${id}`);