jQuery快捷键 - 解除绑定?

3

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

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

这个循环从1到9...

问题是,如果你关闭对话框然后重新打开它,它会不断重新绑定,所以当你按下“1”键时,它会运行两次、三次、四次等等... 它会持续增长。

我尝试在对话框关闭时杀死按键绑定:

$(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');

但是这没有任何效果。有什么想法来处理这个问题吗?
谢谢。

你尝试过使用.die()吗?http://api.jquery.com/die/ - Rafay
3个回答

3
请注意,.unbind() 不支持 eventData 参数,这就是为什么您的解除绑定不起作用的原因。
我可以想到两种不同的方法。如果这些是唯一的文档级别 keydown 绑定,您可以执行“完全”解除绑定,如下所示:
$(document).unbind('keydown'); // unbinds *all* keydown handers on the document

或者,您可以将keydown处理程序存储为非匿名函数,并保留一个引用,在关闭对话框时传递给unbind:

function onkeydown(evt) {
   // do stuff
}

$(document).bind('keydown', '<%=(i+1)%>', onkeydown);

// later, in the dialog's "shutdown" code:
$(document).unbind('keydown', onkeydown);

我不确定在同一函数绑定多次时如何工作。然而,最好消除 eventData,并在事件处理程序中使用 event.which 来确定按下了哪个键(这将只需要绑定处理程序一次)。

1

我使用命名空间和one()方法结合解决了类似的问题。

注意在"keydown.g"中的".g",这将其放置在一个单独的作用域中,以后可以解除绑定而不必解除文档中的每个键按下事件。

$(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


0

您可以使用

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

这个方法在文档加载时只绑定一次事件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接