得到一个新的值输入.innerHTML

时间:2016-03-24 23:52:10

标签: javascript html

我在理解如何从 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>

2 个答案:

答案 0 :(得分:2)

您的代码中有两个错误:

  1. 你正在调用myBalance.innerHTML,但它应该只是myBalance,因为这个变量已经保存了这个值。
  2. 单击按钮时需要更新myBalance变量。目前
  3. 简单的解决方案:只需用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;
    });
    

    另见https://jsfiddle.net/enpo/wdu87Lek/

答案 1 :(得分:1)

您需要在myBalance功能中使用savingSpan切换withBtnmyBalance是一个数字,因此没有attribut innerHTML

withdBtn.addEventListener('click', function() {
    var savAmount = Number(inputAmount.value);
    var withdrawBalance = (savingSpan.innerHTML) - savAmount;
    savingSpan.innerHTML = withdrawBalance;
});

编辑:
对于多个存款,您还需要将myBalance替换为Number(savingSpan.innerHTML)功能中的depBtnmyBalance仅在开头设置一次,因此不代表当前余额。

depBtn.addEventListener('click', function() {
    var savAmount = Number(inputAmount.value);
    var depositBalance = savAmount + Number(savingSpan.innerHTML);
    savingSpan.innerHTML = depositBalance;
});