我正在处理一个奇怪的问题,我需要一个事件处理程序来绑定(bind)模块的实例化,但是当模块通过单击或按键终止时,我不再希望绑定(bind)这个全局事件。我已经获得了点击事件来注册代码中其他地方处理的模块的终止并且可以正常工作,但问题是我想全局终止模块的转义键,无论我的用户当前在应用程序中的哪个位置。
我的问题是 .off() 在这种情况下似乎不起作用。
let tools = {};
//how can i eliminate this next line of code after escape has been triggered?
$(window).on('keydown', (e)=>escape(e, tools));
function escape(e, tools){
if (e.which==27){
//do some stuff with tools, etc
$(window).off('keydown', $(window), escape); //this line doesn't seem to work
alert('alert triggered, but next time escape is pressed it wont.');
}
}
我的这种做法是不是错了?我尝试将它绑定(bind)到 div 元素本身,但这有很多与聚焦 div 以接收按键相关的包袱,如果用户导航到另一个模块,将不再触发转义,因为该模块将不再有重点,好等等等等。
谢谢!
这是 fiddle : https://jsfiddle.net/rbfebL5y/1/
最佳答案
根据 documentation 仅使用处理函数作为参数:
let tools = {};
//how can i eliminate this next line of code after escape has been triggered?
$(window).on('keydown', escape);
function escape(e){
if (e.which==27){
//do some stuff with tools, etc
$(window).off('keydown', escape);
alert('alert triggered, but next time escape is pressed it wont.');
}
}
关于javascript - 触发一次后删除窗口事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48046358/