我可以很好地激活事件监听器,但是让事件监听器在激活后自行删除是我目前无法做到的。到目前为止,从我自己的研究来看,我的理解是附加到事件监听器的函数需要以某种方式命名,删除事件监听器需要能够删除。我试过了,但无法让它工作,因为它会导致不再识别“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
中使用的函数完全相同 - 它不会识别您刚刚在监听器中声明的新函数列表。
关于javascript - 激活事件监听器时删除事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49482757/