我在javascript中制作一个计算器。当我点击添加按钮时,减去它就是调用删除按钮的功能。我的逻辑是首先检查id,然后相应地调用该函数。即使所有按钮都有不同的id,del id条件代码也在运行。
HTML
<div class="row" id="first-row">
<div class="btn red-btn" id="ac">
<p class="text shift-left-sm">AC</p>
</div>
<div class="btn red-btn" id="del">
<p class="text shift-left-sm">DE</p>
</div>
<div class="btn" id="/">
<p class="text number">÷</p>
</div>
<div class="btn rightmost" id="*">
<p class="text number">x</p>
</div>
</div>
的Javascript
const text = document.querySelector("#header-text");
const buttons = document.querySelectorAll(".btn");
const numbers =['1','2','3','4','5','6','7','8','9','0'];
const mathFunc =['ac','del','/','*','-','+','.','equal'];
let displayText ='0';
const firstLetterZeroReg =/0\b/;
for(var i=0;i<buttons.length;i++){
buttons[i].addEventListener('click',function(e){
let attr = this.getAttribute('id');
// when you are pressing a number button
if(numbers.includes(attr)){
if(attr=="0" && lastLetterOfText() =="0"){
//if initially it is zero and you are trying to add more zero. it will stop that
return;
}
if(displayText.match(firstLetterZeroReg)){// regular expression is used which is not necessary at all. Just lazy to remove it
//If initially it is zero and you press the first button zero is erased
displayText =attr;
UpdateDisplay();
return;
}
displayText+=attr;
UpdateDisplay();
}else{
//when you are pressing a function button
// console.log(attr);
// console.log(displayText);
if(attr=="ac"){
EraseEverything();
}else if(attr="del"){
//removes the last letter typed
//PROBLEM IS IN THIS LINE
// This line is being called for other attr too
Del();
}else if(attr!=lastLetterOfText()){
//merely checks if we are not pressing the same button twice
console.log("this also being called");
if(attr==="."){
displayText+=attr;
console.log(displayText);
UpdateDisplay();
}
}else{
console.log("SOme other button is pressed");
}
}
})
}
答案 0 :(得分:1)
您正在使用赋值运算符而不是比较
else if (attr="del")
应该是
else if (attr=="del")