JavaScript:删除调用该EventListener的函数中的EventListener

JavaScript:删除调用该EventListener的函数中的EventListener,javascript,addeventlistener,Javascript,Addeventlistener,我正在尝试使用普通JavaScript、HTML和CSS为浏览器中的计算器创建一个十进制按钮。我遇到的问题是,在使用无意义数字(即3.1.4.0)后,试图关闭十进制按钮,但是我的代码没有达到预期效果: //global constants const calcchoices = Array.from(document.querySelectorAll(".allbtns")); const decimalbtn = document.querySelector("#decimal"); fun

我正在尝试使用普通JavaScript、HTML和CSS为浏览器中的计算器创建一个十进制按钮。我遇到的问题是,在使用无意义数字(即3.1.4.0)后,试图关闭十进制按钮,但是我的代码没有达到预期效果:

//global constants
const calcchoices = Array.from(document.querySelectorAll(".allbtns"));
const decimalbtn = document.querySelector("#decimal");

function buttonpressing(e){

    document.getElementById("display").value += e.target.value //updates the display with what you pressed

    //if decimal is pressed, make sure you cant press it again
    if(e.target.id === "decimal"){
        //turn off the decimal event listener only
        decimalbtn.removeEventListener("click", buttonpressing);
    }
}
calcchoices.forEach(choice => choice.addEventListener("click", buttonpressing))
这是用于此的HTML(有更多的“数字”按钮,如0,但我在本例中删除了它们:

<!DOCTYPE html>
<!--This is the html file for the calculator-->
<html>
<head>
</head>
<body>
    <div id="calculator" class="allbtns">
        <input type="text" name="display" id="display" style="grid-area: display" disabled>
        <!--Numbers-->
        <button id="0" value="0" class="number" style="grid-area:zero">0</button>
        <button id="decimal" class ="number" style="grid-area:decimal" value=".">.</button>
    </div>
</body>
<!-- JS source-->
<script type="text/javascript" src="calculator.js"></script>
</html>

0
.

我不确定为什么我可以删除十进制BTN的EventListener?我怀疑这是调用calcchoices内部的forEach方法的一部分。

您将单击处理程序添加到了
…请尝试
常量calcchoices=Array.from(document.queryselectoral(.allbtns.number”);

然后,您可以使用
this
代替
e.target

const calcchoices=Array.from(document.querySelectorAll(“.allbtns.number”);
const decimalbtn=document.querySelector(“#decimal”);
功能按钮按下(e){
document.getElementById(“display”).value+=this.value;
if(this.id==“十进制”){
此操作。删除EventListener(“单击”,按钮按下);
}
}
calcchoices.forEach(choice=>choice.addEventListener(“单击”,按钮按下))

0
.

您已将单击处理程序添加到
…请尝试
const calcchoices=Array.from(document.querySelectorAll(.allbtns.number));
而不是谢谢,这很有效!但是为什么?为什么选择常规的“allbtns”类禁止我删除EventListener?您将一个事件侦听器添加到一个元素div中-itOk中的输入上没有事件侦听器可以为我清除它。我的印象是EventListener“冒泡”到它的子节点。