我在理解如何从 span id ='savings'中获取新值时遇到一些问题。如您所见,我需要让我的银行帐户有效。如果存款一切都很好,但是当我想提取一些钱时,它从我的起点0开始,而不是从我存入的东西开始。
var inputAmount = document.getElementById('inputAmount');
var withdBtn = document.getElementById('withdBtn');
var savingSpan = document.querySelector('#savings');
var myBalance = Number(savingSpan.innerHTML);
var depBtn = document.getElementById('depBtn');
depBtn.addEventListener('click', function() {
var savAmount = Number(inputAmount.value);
var depositBalance = savAmount + myBalance;
savingSpan.innerHTML = depositBalance;
});
withdBtn.addEventListener('click', function() {
var savAmount = Number(inputAmount.value);
var withdrawBalance = (myBalance.innerHTML) - savAmount;
savingSpan.innerHTML = withdrawBalance;
});
<h1></h1>
<div class="savings" id="accounts">
<h2>Savings Account</h2>
<h3> Your current balance is </h3>
<span>$</span> <span id="savings"> 00.00 </span>
<p>
<input id="inputAmount" type="number" placeholder="Enter amount here">
</p>
<p>
<button id="withdBtn" type="button">Withdraw</button>
<button id="depBtn" type="button">Deposit</button>
</p>
</div>
答案 0 :(得分:2)
您的代码中有两个错误:
简单的解决方案:只需用myBalance替换depositBalance和withdrawBalance。
depBtn.addEventListener('click', function() {
var savAmount = Number(inputAmount.value);
myBalance = savAmount + myBalance;
savingSpan.innerHTML = myBalance;
});
withdBtn.addEventListener('click', function(){
var savAmount = Number(inputAmount.value);
myBalance = myBalance - savAmount;
savingSpan.innerHTML = myBalance;
});
答案 1 :(得分:1)
您需要在myBalance
功能中使用savingSpan
切换withBtn
。 myBalance
是一个数字,因此没有attribut innerHTML
withdBtn.addEventListener('click', function() {
var savAmount = Number(inputAmount.value);
var withdrawBalance = (savingSpan.innerHTML) - savAmount;
savingSpan.innerHTML = withdrawBalance;
});
编辑:
对于多个存款,您还需要将myBalance
替换为Number(savingSpan.innerHTML)
功能中的depBtn
。 myBalance
仅在开头设置一次,因此不代表当前余额。
depBtn.addEventListener('click', function() {
var savAmount = Number(inputAmount.value);
var depositBalance = savAmount + Number(savingSpan.innerHTML);
savingSpan.innerHTML = depositBalance;
});