我有一个 jQuery 对话框,它按如下方式初始化热键:
<script type="text/javascript">
$(document).bind('keydown', '<%=(i+1)%>',function (evt) {
// do stuff
});
</script>
循环 1-9...
问题是,如果您关闭对话框然后重新打开对话框。它不断重新绑定(bind),因此当您按下“1”时,它会运行两次、三次、四次等......它会不断增长。
我尝试终止对话框关闭时的键绑定(bind)
$(document).unbind('keydown', '1');
$(document).unbind('keydown', '2');
$(document).unbind('keydown', '3');
$(document).unbind('keydown', '4');
$(document).unbind('keydown', '5');
$(document).unbind('keydown', '6');
$(document).unbind('keydown', '7');
$(document).unbind('keydown', '8');
$(document).unbind('keydown', '9');
但这没有效果。关于如何处理这个问题有什么想法吗?
谢谢
最佳答案
请注意.unbind()
不支持 eventData
参数,这就是您的取消绑定(bind)不起作用的原因。
在我看来,你有两种不同的方法。如果这些是唯一的文档级 keydown 绑定(bind),您可以按如下方式“完全”取消绑定(bind):
$(document).unbind('keydown'); // unbinds *all* keydown handers on the document
或者,您可以将 keydown 处理程序存储为非匿名函数,并保留引用以在关闭对话框时传回取消绑定(bind):
function onkeydown(evt) {
// do stuff
}
$(document).bind('keydown', '<%=(i+1)%>', onkeydown);
// later, in the dialog's "shutdown" code:
$(document).unbind('keydown', onkeydown);
但是,当同一个函数被多次绑定(bind)时,我并不是 100% 肯定它是如何工作的。您可能最好消除 eventData
并在事件处理程序中使用 event.which
来确定按下了哪个键(这样只需要绑定(bind)一次处理程序) .
关于jQuery 热键 - 解除绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4901720/