jQuery热键 - 解除绑定?

时间:2011-02-04 18:42:35

标签: jquery dialog hotkeys

我有一个jQuery对话框,它按如下方式初始化热键:

<script type="text/javascript">
  $(document).bind('keydown', '<%=(i+1)%>',function (evt) {
     // do stuff
  });
</script>

这循环到1-9 ......

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

我尝试使用

关闭对话框上的键绑定
$(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');

但这没有效果。关于如何处理这个的任何想法?

由于

3 个答案:

答案 0 :(得分:3)

请注意.unbind()不支持eventData参数,这就是你的unbinds无效的原因。

在我的头顶,你有两种不同的方法。如果这些是唯一的文档级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来确定按下了哪个键(这样只需要处理程序绑定一次)。

答案 1 :(得分:1)

我使用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");
 } 
});

&lt; 3 Jquery

答案 2 :(得分:0)

您可以使用

<script type="text/javascript">
$( document ).ready( function() {
    $(document).bind('keydown', '<%=(i+1)%>',function (evt) {
        // do stuff
    });
} );
</script>

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