2011-02-04 124 views
3

我有一个jQuery的对话,其中如下初始化热键: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'); 

杀戮对话框关闭键绑定但是,没有任何效果。有关如何处理这个问题的任何想法?

感谢

+0

你试过`.die()`http://api.jquery.com/die/ – Rafay 2011-02-04 19:18:14

回答

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来确定哪个键被按下(然后只需要处理程序被绑定一次)。

0

您可以使用

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

这种方法结合事件文件加载时一次。

1

我在“keydown.g”使用的keydown事件命名空间连同一个()

注意.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的