This question already has answers here:
How to removeEventListener that is addEventListener with anonymous function?
                            
                                (4个答案)
                            
                    
                3年前关闭。
        

    

我有以下代码:

grabbale.addEventListener("leap-hand-grab", function(e){
if (e.state === "grab") {
            console.log("grabbed");
} else if (e.state === "release") {
            console.log("release");
} else if (e.state === "move") {
    if (stopGrab == 0) {
        grabbale.style.left = e.x - (grabbale.offsetWidth/2)+ "px";
        grabbale.style.top = e.y - (grabbale.offsetHeight/2)+ "px";
    } else {
        $("#foo").css({
        "color": "red"
        });
    }
}


})

我需要使用removeEventListener删除eventListener,但是它需要两个参数,即事件和函数。
就我而言,函数没有名称,而事件是grabbale元素的拖动...
我该怎么做?

最佳答案

好了,您可以改用命名函数,这是相同的,只有匿名函数现在有了名称。

grabbale.addEventListener("leap-hand-grab", grabListener);

function grabListener(e){
    if (e.state === "grab") {
        console.log("grabbed");
    } else if (e.state === "release") {
        console.log("release");
    } else if (e.state === "move") {
        if (stopGrab == 0) {
            grabbale.style.left = e.x - (grabbale.offsetWidth/2)+ "px";
            grabbale.style.top = e.y - (grabbale.offsetHeight/2)+ "px";
    } else {
        $("#foo").css({
        "color": "red"
        });
    }
}


对于删除只是使用

grabbale.removeEventListener("leap-hand-grab", grabListener);


您需要在哪里删除事件。

一些额外的链接:


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function#Named_function_expression

关于javascript - removeEventListener,在特殊情况下如何执行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41348027/

10-12 15:44