Javascript事件侦听器在错误的元素上工作?
我正在用javascript制作一个计算器。当我点击像add,subtract这样的按钮时,它调用了delete按钮的功能。我的逻辑是先检查id,然后相应地调用函数。即使所有按钮都有不同的id,del id条件代码仍在运行 HTMLJavascript事件侦听器在错误的元素上工作?,javascript,Javascript,我正在用javascript制作一个计算器。当我点击像add,subtract这样的按钮时,它调用了delete按钮的功能。我的逻辑是先检查id,然后相应地调用函数。即使所有按钮都有不同的id,del id条件代码仍在运行 HTML AC DE x Javascript const text = document.querySelector("#header-text"); const buttons = document.querySelectorAll(".btn");
AC
DE
x
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");
}
}
})
}
const text=document.querySelector(“标题文本”);
const buttons=document.queryselectoral(“.btn”);
常量数=['1','2','3','4','5','6','7','8','9','0'];
常量mathFunc=['ac'、'del'、'/'、'*'、'-'、'+'、'.'相等'];
让displayText='0';
常量firstLetterZeroReg=/0\b/;
对于(var i=0;i您使用赋值运算符而不是比较运算符
else if (attr="del")
应该是
else if (attr=="del")
此
没有指向所讨论的元素。这是一个jQuery问题。您需要使用e.target
来代替它。谢谢。但是它适用于数字按钮,如1,2,3,而this.getattr可以work@Amy那不是真的
else if (attr=="del")