首页 > 解决方案 > JavaScript:在调用该 EventListener 的函数中删除 EventListener

问题描述

我正在尝试使用 vanilla 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>

我不确定为什么我可以为 decimalbtn 删除那个 EventListener?我怀疑这是在 calcchoices 中调用 forEach 方法的一部分。

标签: javascriptaddeventlistener

解决方案


您将点击处理程序添加到<div id="calculator" class="allbtns">... 尝试const calcchoices = Array.from(document.querySelectorAll(".allbtns .number"));改为

然后,您也可以使用this而不是e.target

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

function buttonpressing(e) {
  document.getElementById("display").value += this.value;
  if (this.id === "decimal") {
    this.removeEventListener("click", buttonpressing);
  }
}
calcchoices.forEach(choice => choice.addEventListener("click", buttonpressing))
<div id="calculator" class="allbtns">
  <input type="text" name="display" id="display" style="grid-area: display" disabled>
  <!--Numbers-->
  <button id="d0" value="0" class="number" style="grid-area:zero">0</button>
  <button id="decimal" class="number" style="grid-area:decimal" value=".">.</button>
</div>


推荐阅读