激活事件监听器时删除事件监听器

Removing Event Listener when Event Listener is Activated

我可以很好地激活事件侦听器,但是让事件侦听器在激活后自行删除是我目前无法做到的。到目前为止,我自己尝试研究这个问题,我的理解是附加到事件侦听器的函数需要以某种方式命名,删除事件侦听器需要能够删除。我试过了,但无法让它工作,因为它导致不再识别 'e' 的问题。这是我的代码:

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');
};

将函数放在一个变量中,这样你以后使用时可以引用它removeEventListener。例如

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');
    }
}

removeEventListener 的第二个参数必须与 addEventListener 中使用的函数完全相同 - 它不会识别您刚刚在侦听器列表中声明的新函数。