removeEventListener()不适用于在HTML5文件中添加的事件

时间:2019-04-02 17:13:22

标签: javascript html5 dom-events

我正在尝试删除在HTML5文件中设置的按钮上设置的事件侦听器,但似乎并没有将其删除。

HTML5文件:

<!DOCTYPE html>
<html>
<head>
    <script src="lab5v1js.js"></script>
</head>
<body onload="loadPuzzle()">
<table>
    <tbody>
       ..........................
    </tbody>
</table>
<button id="button" onmousedown="solve();" onmouseup="checkIfSolved()">SOLVE!</button>
</body>
</html>

JS文件:

function checkIfSolved() {
    .......................
    //here it is ok, so remove handlers
    document.getElementById("button").removeEventListener("mousedown", solve);
    document.getElementById("button").removeEventListener("mousedown", checkIfSolved);

    alert("SOLVED!");
}

我尝试在尝试删除事件侦听器之前和之后打印document.getElementById(“ button”)的结果,但是似乎没有效果(它们没有被删除)...

这可能是什么原因?

1 个答案:

答案 0 :(得分:0)

您需要清除方法,而不是删除侦听器

const solve = () => console.log('solve test');

function checkIfSolved() {

    //here it is ok, so remove handlers
    document.getElementById("button").onmousedown = undefined;

    alert("SOLVED!");
}
<table>
    <tbody>
       ..........................
    </tbody>
</table>
<button id="button" onmousedown="solve();" onmouseup="checkIfSolved()">SOLVE!</button>
</body>

如果要使用事件监听器:

const solve = () => console.log(`solve test - ${Date.now()}` );
function checkIfSolved() {

    document.querySelector("#button").removeEventListener('mousedown', solve);
    alert("SOLVED!");
}

document.addEventListener('DOMContentLoaded', () => {
  // Add our click
  let btn = document.querySelector('#button');
  btn.addEventListener('mousedown', solve);
  btn.addEventListener('mouseup', checkIfSolved); 
});
<table>
    <tbody>
       ..........................
    </tbody>
</table>
<button id="button">SOLVE!</button>
</body>