簡體   English   中英

計算器,如何在單擊加號后存儲一個值並在單擊等號后給出總和?

[英]Calculator, how can I store a value after click on plus symbol and give the sum after click on equal symbol?

我正在制作一個計算器,但在單擊加號后存儲值時出現問題,然后選擇另一個數字單擊等號並獲得結果。 請幫幫我! 經驗值

let firstValue;
let secondValue;

document.querySelector('#addOperator').addEventListener('click', function() {
 if(document.querySelector('#addOperator')) {
  firstValue = document.querySelector('#output').textContent;
  // document.querySelector('#output').textContent = '';
  // console.log(firstValue);
  console.log(document.querySelector('#output').textContent);
 };
});

document.getElementById('equals').addEventListener('click', function() {
 if(document.querySelector('#output').textContent === firstValue) {
  secondValue = document.querySelector('#output').textContent;
  // console.log(secondValue);
  // document.querySelector('#output').textContent = add(firstValue, secondValue);
  console.log(document.querySelector('#output').textContent = add(firstValue, secondValue));
 };
});

我的 html 文檔是這個--------------------------------------------- ---------------->

    <!-- Calculator display  -->
<div id="output">
  <!-- <div id="previous-operand"></div>
  <div id="current-operand"></div> -->
</div>

<button class="span-two" id="ac-color">AC</button>
<button id="clear-entry">CE</button>
<button id="divideOperator">÷</button>
<button class="number">7</button>
<button class="number">8</button>
<button class="number">9</button>
<button id="multiplyOperator">*</button>
<button class="number">4</button>
<button class="number">5</button>
<button class="number">6</button>
<button id="addOperator">+</button>
<button class="number">1</button>
<button class="number">2</button>
<button class="number">3</button>
<button id="subtractOperator">-</button>
<button class="number">0</button>
<button class="number">.</button>
<button class="span-two" id="equals">=</button>

這會起作用我沒有添加添加按鈕,只是當你點擊操作時,設置一個標志來檢查你點擊計算時是否說它是否是加/減等

<input type="button" value="1" onclick="add(event)" />
<input type="button" value="2" onclick="add(event)"/>
<input type="button" value="3" onclick="add(event)"/>
<input type="button" value="4" onclick="add(event)"/>
<input type="button" value="Equals" onclick="calculate()"/>
...
<script>
var nums = [];

var add = function(e){
  nums.push(Number(e.target.value));
}

var calculate = function(){
  var res =0;
  if(nums.length > 0){  
    nums.forEach(function(num){
      res += num;
    });
  }
  alert(res);
  return res;
}
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM