简体   繁体   English

激活事件侦听器后删除事件侦听器

[英]Removing Event Listener when Event Listener is Activated

I get the event listeners activated just fine, but getting the event listener to remove itself after it has been activated is thus far eluding me. 我可以很好地激活事件侦听器,但是到目前为止,让事件侦听器在被激活后将其自身删除是无法理解的。 From trying to research this on my own so far, my understanding is that the function attached to the event listener somehow needs to be given a name which removing the event listener requires to be able to remove. 到目前为止,从我自己进行研究的角度来看,我的理解是,需要以某种方式为附加到事件侦听器的函数指定一个名称,该名称必须能够删除该事件侦听器。 I tried that, but couldn't get it to work as it then resulted in problems with no longer recognizing 'e' anymore. 我试过了,但无法使其正常工作,因为这导致不再识别“ e”的问题。 Here is my code: 这是我的代码:

that.enter = function(imageID, textID) {
    // Listen for the ENTER key and mouse click.
    console.log('Add event listeners...');
    console.log(imageID + ' ' + textID);
    document.addEventListener('keydown', function(e) { 
        if (e.which === 13) {
            document.getElementById(imageID).click();
            console.log('keydown activated');
            console.log('removing keydown... ');
            document.removeEventListener('keydown', function(e){});
            console.log('keydown removed');
        }
    });
    document.addEventListener('click', function(e) { 
        if (e.target.id != imageID && e.target.id != textID) {
            document.getElementById(imageID).click();
            console.log('click activated');
            console.log('removing click... ');
            document.removeEventListener('click', function(e){});
            console.log('click removed');
        }
    });
    console.log('DONE');
};

Put the function in a variable, that way you can reference it later when you use removeEventListener . 将函数放在变量中,这样以后可以在使用removeEventListener时引用它。 Eg 例如

document.addEventListener('keydown', theListener);
function theListener(e) { 
    if (e.which === 13) {
        document.getElementById(imageID).click();
        console.log('keydown activated');
        console.log('removing keydown... ');
        document.removeEventListener('keydown', theListener);
        console.log('keydown removed');
    }
}

The second argument to removeEventListener must be the exact same function that was used in addEventListener - it won't recognize a new function you just declared as being in the listener list. removeEventListener的第二个参数必须与addEventListener中使用的功能完全相同-它不会识别您刚刚声明为在侦听器列表中的新功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM