我可以很好地激活事件侦听器,但是到目前为止,让事件侦听器在被激活后将其自身删除是无法理解的。到目前为止,从我自己尝试研究这一点开始,我的理解是,需要以某种方式为附加到事件侦听器的函数指定一个名称,该名称必须能够删除该事件侦听器。我试过了,但无法使其正常工作,因为这导致不再识别'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
-它不会识别您刚刚声明为在侦听器列表中的新函数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句