javascript - 按“=”后清除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 = "";
}
}
解决方案
您可以有一个变量来跟踪计算的状态。如果已计算,清除显示并重置状态
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
}
推荐阅读
- php - 在 localhost/phpmyadmin 中获取目录列表而不是登录菜单
- google-apps-script - 当数字改变时创建/替换时间戳(谷歌脚本)
- javascript - 使用 UI 登录测试的节点
- mongodb - dyld:找不到符号:_syslog$DARWIN_EXTSN:mongoDb
- arrays - 在 Swift UI 中的结构数组上运行函数
- python - 我的 Python MAC_changer 程序在 if elif 和 else 语句部分有问题
- python - 在 Google Colab 上的 R 笔记本中安装 python 库
- python - 检查两个数据帧之间的部分字符串匹配
- python - 调用具有不同名称的函数
- excel - 将值复制到不同的工作簿