Как сохранить, восстановить и очистить значение в JavaScript? - PullRequest
0 голосов
/ 17 апреля 2020

Я пытаюсь сделать калькулятор в javascript, и я пытаюсь сделать кнопки памяти, используя события onclick. Я хочу, чтобы значения на моем экране (скажем, 8 + 8 = 16) сохранялись при нажатии кнопки MS. Затем скажите, что если я очищаю экран с помощью кнопки C, делаю еще один расчет (скажем, 9+ 10 = 19), затем я хочу вернуть первый расчет и нажимаю MR. Затем, наконец, если я хочу избавиться от памяти хранилища, я нажму M C, и все значения MS и MR будут очищены.

JS:


//Changing colors of operation colors 

//Multiply Color
const colorMultiply = document.getElementById('multiply')
      colorMultiply.style.backgroundColor = "green" //Makes Color Green

//Divide Color
const colorDivide = document.getElementById('divide')
      colorDivide.style.backgroundColor = "red"//Makes Color Red

//subtract color
const colorSubtract = document.getElementById('subtract')
      colorSubtract.style.backgroundColor="blue"//Makes Color Blue

//add color
const colorAdd = document.getElementById('add')
      colorAdd.style.backgroundColor="yellow"//Makes Color Yellow


//change font of numbers to blue (I did it like this incase anyone wants to color of a single number)
//Makes it easier for you to change a colour of one button.
const number1 = document.getElementById('number1')
number1.style.color="blue"
const number2 = document.getElementById('number2')
number2.style.color="blue"
const number3 = document.getElementById('number3')
number3.style.color="blue"
const number4 = document.getElementById('number4')
number4.style.color="blue"
const number5 = document.getElementById('number5')
number5.style.color="blue"
const number6 = document.getElementById('number6')
number6.style.color="blue"
const number7 = document.getElementById('number7')
number7.style.color="blue"
const number8 = document.getElementById('number8')
number8.style.color="blue"
const number9 = document.getElementById('number9')
number9.style.color="blue"
const number0 = document.getElementById('number0')
number0.style.color="blue"
const decimal = document.getElementById('decimal')
decimal.style.color="blue"

//Changing color of the clear button
const clear = document.getElementById('clear')
clear.style.color="white"
clear.style.backgroundColor="black"

var buttons = document.getElementsByTagName('button');
for (var i = 0; i < buttons.length; i++) {   
      //Event Listener for mouseenter
      buttons[i].addEventListener("mouseover", function( event ) {   
    // highlight the mouseenter target
    event.target.style.backgroundColor = "black";

    // reset the color after a short delay
    setTimeout(function() {
      event.target.style.backgroundColor = "";
      //Changing colors of operation colors 

//Revert all the operator buttons
colorMultiply.style.backgroundColor ="green" //Makes Color Green
colorDivide.style.backgroundColor = "red"//Makes Color Red
colorSubtract.style.backgroundColor="blue"//Makes Color Blue
colorAdd.style.backgroundColor="yellow"//Makes Color Yellow
clear.style.backgroundColor="black"//Makes color Black

    }, 500);
  }, false);

}


// Then we want to insert `memoryStoreButton` before the `clear` button:
var memoryStoreButton = document.createElement("BUTTON");
    memoryStoreButton.innerHTML = "MS";
    clear.before(memoryStoreButton); //puts button before clear

// Then we want the `memoryClearButton` before `memoryStoreButton`
var memoryClearButton = document.createElement("BUTTON");
    memoryClearButton.innerHTML = "MC";
    memoryStoreButton.before(memoryClearButton);//puts button before clear

// and finally, the `memoryRestoreButton` before `memoryClearButton`
var memoryRestoreButton = document.createElement("BUTTON");
    memoryRestoreButton.innerHTML = "MR";
    memoryClearButton.before(memoryRestoreButton);//puts button before clear

//What number buttons are pressed
var numButton = document.querySelectorAll(".btn8");
var showNum = document.querySelector(".screen8");

numButton.forEach(function(button){
  button.addEventListener('click', function(event){
    if(event.target.innerHTML == "C"){
      return showNum.value = "";
    } else if (event.target.innerHTML == "=") {
      return;
    }
    let view = event.target.dataset.num;
    showNum.value += view;
  });
});


//When equal is pressed it calculates the numbers, and if no numbers were entered there will be a error mesage
var equalButton = document.querySelector("#equals")
equalButton.addEventListener('click', function(event){
  if(showNum.value == ""){
    return alert("Please Enter a Value"); // If no numbers are being displayed, error alert.
  }
  showNum.value = showNum.value + "=" + eval(showNum.value);
});

//Align test to the right of screen
document.getElementById("numberBox").style.textAlign = "right";

//Make the memorty buttons
memoryStoreButton.onclick = (function(){
  var memValue = document.querySelector(".screen8").value
  return memValue
})

memoryRestoreButton.onclick = (function(){
  showNum.value = memValue
})

memoryClearButton.onclick = (function(){
    memValue = ""
})

HTML:

<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">

<title> Calculator 8 </title>
 <script src="fp.js" defer></script>
 <link rel="stylesheet" href="fp.css">



</head>

<body>
 <section class="calculator8">
    <h1> Calculator 8 </h1>
  <form>
   <input type="text" name="calcScreeng" id="numberBox" class="screen8">
  </form>
  <div class="buttons8"> 
   <!-- operation buttons -->
   <button id="multiply" type="button" class="btn8 btn-mul" data-num="*">*</button>
   <button id="divide" type="button" class="btn8 btn-div" data-num="/">/</button>
   <button id="subtract" type="button" class="btn8 btn-sub" data-num="-">-</button>
   <button id="add" type="button" class="btn8 btn-add" data-num="+">+</button>
   <!-- number buttons -->
   <button id="decimal" type="button" class="btn8 btn-grey" data-num=".">.</button>
   <button id="number9" type="button" class="btn8 btn-grey" data-num="9">9</button>
   <button id="number8" type="button" class="btn8 btn-grey" data-num="8">8</button>
   <button id="number7" type="button" class="btn8 btn-grey" data-num="7">7</button>
   <button id="number6" type="button" class="btn8 btn-grey" data-num="6">6</button>
   <button id="number5" type="button" class="btn8 btn-grey" data-num="5">5</button>
   <button id="number4" type="button" class="btn8 btn-grey" data-num="4">4</button>
   <button id="number3" type="button" class="btn8 btn-grey" data-num="3">3</button>
   <button id="number2" type="button" class="btn8 btn-grey" data-num="2">2</button>
   <button id="number1" type="button" class="btn8 btn-grey" data-num="1">1</button>
   <button id="number0" type="button" class="btn8 btn-grey" data-num="0">0</button>
   <button id="equals" type="button" class="btn8 btn-grey">=</button>
   <button id="clear" type="button" class="btn8 btn-grey">C</button>


  </div>



 </section>


</body>

</html>

CSS:

*{
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}

body{
 min-height: 100vh;
 display: flex;
 align-items: center;
 justify-content: center;

}

.calculator8{
 flex: 0 0 40%;
}
.screen8{
 width: 100%;
 font-size: 5rem;
 padding: 0.5rem;
 background: rgb(41,41,56);
 color: white;
 border:none;
}

.buttons8{
 display: flex;
 flex-wrap: wrap;
 transition: all 0.5s linear;
}

button{
 flex:0 0 25%;
 border: 1px solid black;
 padding: 0.25rem 0;
 transition: all 2s ease;
}

.btn-kground: rgb(224,224,224);
}

.btn8{
 font-size: 4rem;
}

1 Ответ

0 голосов
/ 17 апреля 2020

Есть несколько способов сделать это. Вероятно, самым простым было бы просто сделать memValue глобальной переменной. Как то так:

var memValue = "";

//Make the memorty buttons
memoryStoreButton.onclick = (function(){
  memValue = document.querySelector(".screen8").value
})

memoryRestoreButton.onclick = (function(){
  showNum.value = memValue
})

memoryClearButton.onclick = (function(){
    memValue = ""
})
...