计算器清除按钮

时间:2016-01-27 00:12:09

标签: javascript calculator

我正在尝试为计算器添加一个清除按钮。我希望它将数组重置为空,即storage.length = 0;。但是,我无法让我的AC键做任何事情......我试着让它提醒'嗨',但没有。我是新手,所以我迷失了。

/* Click on button and have number saved in array for later use*/

var calcKeys = document.querySelectorAll('.num');
var storage = ['1'];

function addClick(node) {
  node.addEventListener('click', function(e) {
    storage.push(e.target.innerHTML);
    console.log(storage);
    
    if(calcKeys.innerHTML === 'AC') {
      alert("hi");
      /*storage.length = 0;*/
    }
  });
}

for (var i = 0; i < calcKeys.length; i++) {
  addClick(calcKeys[i]);
}

// when user clicks AC button, clear array

// get node by defining AC key


console.log(storage);
#calculator{
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 255, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 10px;
}

.keys {
  display: flex;
  justify-content: space-around;
  width: 100%;
  flex-wrap: wrap;
  max-width: 250px;
}

.keys span {
  padding: 20px;
  border-radius: 5px;
  margin: 8px;
  font: bold 20px Arial, sans-serif;
  display: flex;
  align-items: center;
  background-color: grey;
}

.keys span:nth-child(odd) {
  background-color: aqua;
}

.screen {
  width: 95%;
  height: 40px;
  border-radius: 3px;
  background-color: #ccc;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <div id="calculator">
    <div class="screen"></div>
    <div class="keys">
      <span class="num">1</span>
      <span class="num">2</span>
      <span class="num">3</span>
      <span class="num">4</span>
      <span class="num">5</span>
      <span class="num">6</span>
      <span class="num">7</span>
      <span class="num">8</span>
      <span class="num">9</span>
      <span class="num">0</span>
      <span class="num operator plus">+</span>
      <span class="num operator minus">-</span>
      <span class="num operator divide">/</span>
      <span class="num operator times">*</span>
      <span class="num operator ac">AC</span>
    </div>
  </div>
</head>
<body>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

问题在于:

function addClick(node) {
    node.addEventListener('click', function(e) {
    storage.push(e.target.innerHTML);
    console.log(storage);
    /* Here */
    if(calcKeys.innerHTML === 'AC') {
        alert("hi");
   /*storage.length = 0;*/
   }
});
}

您使用calcKeys购买,而不是使用当前密钥,因此您必须纠正此问题:

function addClick(node) {
    node.addEventListener('click', function(e) {
        storage.push(e.target.innerHTML);
        console.log(storage);

        if(e.target.innerHTML === 'AC') {
            alert("hi");
            /*storage.length = 0;*/
        }
   });

}