我试图在单击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未正确执行。

检查部分:

最佳答案

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



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是一个不同的对象,因此mouseOverPathaddEventListenerremoveEventListenerremoveEventListener引用不同的对象,并且从mouseOverPath开始不执行任何操作。

如果使用setPath功能,则需要将功能移出。

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



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()

09-20 00:33