Javascript 事件侦听器处理错误的元素



我正在用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>

爪哇语

 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 =/0b/;
    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")

最新更新