javascript - 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 方法的一部分。
解决方案
您将点击处理程序添加到<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>
推荐阅读
- agda - 来自标准库“less”的内置“less”
- composer-php - 在 composer.json 中排除文件更新
- angular - 使用 Cypress 测试 Angular 时如何防止整页重新加载?
- java - 获取 Java 和 C# 之间的匹配校验和
- sql-server - 如何根据用户 SSRS 角色分配过滤 SSRS 中的数据
- python - 根据标准获取 Python Pandas 中的第一行数据框,而无需遍历整个数据框
- javascript - 如何根据选项的值设置只读选择的样式?
- google-apps-script - 无法从通用操作的回调函数返回卡片标记
- c# - 在 C# 中仅复制新的或修改的文件/目录
- javascript - Using Conditional If statements with JavaScript DOM Table?