Javascript 如何解除绑定特定的事件处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3972886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to unbind a specific event handler
提问by MeProtozoan
Code:
代码:
$('#Inputfield').keyup(function(e)
{
if(e.which == 13)
{
functionXyz();
}
else
{
functionZyx();
}
});
$(document).keyup(function(exit) {
if (exit.keyCode == 27) { functionZzy(); }
});
Question:How to remove the keyup event handler of keyCode == 27 and keep the other $(document).keyup event handlers intact?
问题:如何删除 keyCode == 27 的 keyup 事件处理程序并保持其他 $(document).keyup 事件处理程序完好无损?
回答by Nick Craver
You have to use a named function so you can reference that specific handler when calling .unbind()
, like this:
您必须使用命名函数,以便在调用 时可以引用该特定处理程序.unbind()
,如下所示:
function keyUpFunc(e) {
if (e.keyCode == 27) { functionZzy(); }
}
$(document).keyup(keyUpFunc);
Then later when unbinding:
然后在解除绑定时:
$(document).unbind("keyup", keyUpFunc);
回答by Felix Kling
Your are attaching the event handlers to different elements, so you can safely remove the handler from the specific object (already mentioned I know).
您将事件处理程序附加到不同的元素,因此您可以安全地从特定对象中删除处理程序(我知道已经提到过)。
For the sake of completeness, if you want to attach multiple handlers for the same event to the sameobject, you can use namespaced events:
为了完整起见,如果要将同一事件的多个处理程序附加到同一对象,可以使用命名空间事件:
$('#Inputfield').bind('keyup.keep', function(e){/*...*/});
$('#Inputfield').bind('keyup.notkeep', function(e){/*...*/});
$('#Inputfield').unbind('keyup.notkeep');
// or event $('#Inputfield').unbind('.notkeep');
Since jQuery 1.7, the methods .on
and .off
are the preferred way to add and remove event handlers. For this purpose they behave exactly like .bind
and .unbind
and also work with namespaced events.
从jQuery 1.7 开始,方法.on
和.off
是添加和删除事件处理程序的首选方式。为此,它们的行为与命名空间事件完全相同.bind
,.unbind
并且也与命名空间事件一起使用。
回答by Dan D.
jQuery allows you to bind events that will be unbound after their first invocation. If you are looking to only run this keyup function once, look at the .one() method listed here: http://api.jquery.com/one/
jQuery 允许您绑定将在第一次调用后解除绑定的事件。如果您只想运行此 keyup 函数一次,请查看此处列出的 .one() 方法:http: //api.jquery.com/one/
$(document).one('keyup', function(e) {
if (e.keyCode == 27) { functionZzy(); }
});
回答by lonesomeday
If you only have one handler on an element, you can safely unbind it using unbind
without using named functions as Nick Craver suggests. In this case, calling
如果您在一个元素上只有一个处理程序,您可以安全地解除它的绑定,unbind
而无需使用 Nick Craver 建议的命名函数。在这种情况下,调用
$('#Inputfield').unbind('keyup');
will not affect the handler on document
.
不会影响 上的处理程序document
。