jQuery热键 – 取消绑定?

我有一个jQuery对话框初始化热键如下:

 $(document).bind('keydown', '',function (evt) { // do stuff });  

这循环到1-9 ……

问题是,如果关闭对话框然后重新打开对话框。 它保持重新绑定,所以当你在’1’上执行keydown时,它会运行twices,三次,四次等等……它只是不断增长。

我尝试在关闭对话框中杀死键绑定

 $(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参数,这就是你的.unbind()原因。

在我的头顶,你有两种不同的方法。 如果这些是唯一的文档级keydown绑定,您可以进行“完全”解除绑定,如下所示:

 $(document).unbind('keydown'); // unbinds *all* keydown handers on the document 

或者,您可以将keydown处理程序存储为非匿名函数,并在关闭对话框时保留引用以返回取消绑定:

 function onkeydown(evt) { // do stuff } $(document).bind('keydown', '<%=(i+1)%>', onkeydown); // later, in the dialog's "shutdown" code: $(document).unbind('keydown', onkeydown); 

然而,当多次绑定相同的函数时,我不是100%肯定的。 你可能最好除去eventData并在事件处理程序中使用event.which来确定按下了哪个键(这将只需要处理程序绑定一次)。

我使用keydown事件的命名空间和one()一起解决了类似的问题

请注意“keydown.g”中的.g。 这将它放在一个单独的范围内,我可以在以后取消绑定而不解除文档中的每个keydown。

 $(document).one("keydown.g", function(e) { // tab key if (e.which == "9") { e.preventDefault(); // do something like focus on a field $("#target").focus(); // once you've moved the focus, you can unbind and go back to tabbing normally $(document).unbind("keydown.g"); } }); 

<3 Jquery

您可以使用

  

此方法在加载文档时将事件绑定一次。