首页 > 解决方案 > 按“=”后清除javascript计算器中的显示

问题描述

我是编码新手,我构建了一个 Javascript 计算器,但在完成一次计算后,我无法清除显示。相反,第一次计算的结果进入第二次计算的输入。例如,如果我执行 3+5,它会给我 8,但如果我然后按 4,显示屏会显示 84,这就是它出现问题的原因。我可以通过清除按钮清除屏幕,但每次计算后都会变得乏味。谢谢你。

//select all the buttons
const buttons = document.querySelectorAll('button');

//select the <input type="text" class+"display" disabled> element
const display = document.querySelector('.display');

//add eventListener to each button
buttons.forEach(function(button) {
button.addEventListener('click',calculate);
});

//calculate function
   function calculate(event) {
   //current clicked buttons value
   var clickedButtonValue = event.target.value;

   if(clickedButtonValue === '=') {

       //check if the display is not empty then only do the calculation
       if(display.value !== "") {

           //calculate and show the answer to display
           display.value = eval(display.value);
       }

       //if any key except "=" pressed again clear display
       button.addEventListener('click',clearDisplay);

   } else if (clickedButtonValue === 'C') {

       //clear everything on display
       display.value = "";

   } else {

       //otherwise concatenate it to the display
       display.value += clickedButtonValue;
   }
}

function clearDisplay(clickedButtonValue) {
    if(clickedButtonValue !== "=") {
        display.value = "";
    }
}

标签: javascriptcalculator

解决方案


您可以有一个变量来跟踪计算的状态。如果已计算,清除显示并重置状态

var calculated = false;

function calculate( event ){
    var clickedButtonValue = event.target.value;

    if ( calculated ) {
        display.value = "";

        calculated = false;
    }

    if(clickedButtonValue === '=') {
        if(display.value !== "") {

            //calculate and show the answer to display
            display.value = eval(display.value);

            calculated = true;
        }
    }
    // the rest of your logic here
}

推荐阅读