如何停止DOM javascript事件处理程序

How to stop DOM javascript event handler

本文关键字:事件处理 程序 javascript DOM 何停止      更新时间:2023-09-26

我有以下代码,意图停止处理鼠标点击网页,在第一次鼠标点击之后。

    // The following is inside the onload function of html BODY.
    var     theLeftSide     = document.getElementById("leftSide");
    var     theBody         = document.getElementsByTagName("body")[0];
    theBody.addEventListener("click",  function() {
        gameOver( theLeftSide, theBody );
    });
    ....................
    function gameOver(theLeftSide, theBody){  
        alert("That is not the correct face. Game over.");
        theBody.onclick = null;
        theLeftSide.lastChild.onclick = null;
    }

但是,鼠标处理不会停止(如警报所示)。我做了一些搜索,以确认javascript通过引用传递"对象参数"。当我通过调试器时,我看到事件处理程序(theBody.onclick)被设置为NULL。为什么gameOver()的改变不影响网页主体?


更新:感谢所有的评论。虽然我在发完帖子后休息的时候意识到了自己的错误,但所有的回复都对我学习以前不知道的东西很有帮助,特别是因为它们促使我进一步阅读文档。我必须修改公认的答案,因为变量是局部的,而不是全局的。因此,解决我的问题的当前代码看起来像这样::

    theBody.addEventListener("click",  function clickListener() {
        gameOver( theLeftSide, theBody, clickListener );
    });
    And outside the function where the above statement is, i have
    function gameOver(theLeftSide_param, theBody_param, clickListener_param) {
        alert("That is not the correct face. Game over.");
        theBody_param.removeEventListener("click", clickListener_param);
        theLeftSide_param.lastChild.onclick = null;
    }        

clickListener必须作为参数传递,因为它不是全局的,并且在gameOver()之外不可见。

设置onclick属性不会以任何方式影响使用.addEventListener()添加的事件处理程序。如果你想删除这些事件处理程序,那么你可以对它们使用.removeEventListener()

注意:暂时阻止所有点击事件的常用技术是在所有内容上面插入一个透明div,它将抓取所有的点击事件,然后在该透明div上使用一个点击处理程序来停止传播。当有许多不同的even处理程序时,可以使用这种技术,其中一些可能您甚至不能直接控制,或者您只想暂时阻止它们,然后稍后再恢复它们。

使用addEventListener分配的事件处理程序不在onclick属性中(因为它只能容纳一个函数,并且您可以添加任意数量的侦听器)。使用removeEventListener删除用addEventListener添加的处理器

由于您需要为this提供侦听器函数,并且它必须与添加的函数相匹配,因此您应该将该函数移出到命名函数中,因为两个匿名函数永远不会相等。

function clickListener() {
    gameOver(theLeftSide, theBody);
}
theBody.addEventListener("click", clickListener);
function gameOver(theLeftSide, theBody) {
    alert("That is not the correct face. Game over.");
    theBody.removeEventListener("click", clickListener);
    theLeftSide.lastChild.onclick = null;
}

如果你想在第一次点击后停止鼠标点击,那么你可以在第一次鼠标点击后放置一个div覆盖,很难100%确定这是否是你正在寻找的答案。

演示:

HTML:

<div id="dis_click"></div>
<button type="button" onclick="alert ('You clicked me')">Click me first!</button>
<button type="button" onclick="alert ('you didnt follow the instructions!')">then after click me!</button>
CSS:

.overlay {
    position: absolute;
    width:100%;
    height:100%;
    background-color: rgba(1, 1, 1, 0);
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;
}
JavaScript:

document.onmouseup = myMouseUpHandler;
function myMouseUpHandler(){  
    document.getElementById("dis_click").className = "overlay";
}