gpt4 book ai didi

javascript - 单击时未删除 eventListener

转载 作者:行者123 更新时间:2023-11-30 08:20:04 24 4
gpt4 key购买 nike

我试图在单击 Canvas 元素时删除 eventListener:

document.getElementById("canvas")
.addEventListener("click", setPath, false);

function setPath() {
if (check) {
document.getElementById("canvas").
addEventListener("mousemove", mouseOverPath, false);
} else {
document.getElementById("canvas").
removeEventListener("mousemove", mouseOverPath, false);
}

function mouseOverPath(event) {
drawLine.x = event.clientX;
drawLine.y = event.clientY;
drawLine.draw();
}

}

document.getElementById("canvas").
addEventListener("click", () => {
if (check == true) {
check = false;
} else if (check == false) {
check = true;
}
}, false);
<canvas id="canvas" height="200" width="200" style="border:1px solid black;">

if 语句已正确执行,但 removeEventListener 未正确执行。

校验部分:

最佳答案

您的问题是您在 setPath 中定义了 mouseOverPath:

function setPath() {
if (check) {
document.getElementById("canvas").addEventListener("mousemove", mouseOverPath, false);
} else {
document.getElementById("canvas").removeEventListener("mousemove", mouseOverPath, false);
}

function mouseOverPath(event) {
drawLine.x = event.clientX;
drawLine.y = event.clientY;
drawLine.draw();
}

}

对于 setPath 的每次调用,mouseOverPath 都是不同的对象,因此 addEventListenermouseOverPathremoveEventListener 引用不同的对象,而 removeEventListener 什么都不做。

如果setPath 函数,您需要将mouseOverPath 函数移出。

这里是您问题的简化测试用例:

var tmp;

function test() {
if (!tmp) {
// save the current foo for the first call of test
tmp = foo
} else {
// the comparison of the current foo with tmp (the previous foo) is false
console.log(tmp == foo)
}

function foo() {}
}

test()
test()

关于javascript - 单击时未删除 eventListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54930754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com