gpt4 book ai didi

Javascript 事件监听器在错误的元素上工作?

转载 作者:行者123 更新时间:2023-12-03 02:41:05 25 4
gpt4 key购买 nike

我正在用 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");
}
}
})
}

最佳答案

您使用的是赋值运算符而不是比较

 else if (attr="del")

应该是

 else if (attr=="del")

关于Javascript 事件监听器在错误的元素上工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48325622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com