简体   繁体   English

如何取消绑定特定的事件处理程序

[英]How to unbind a specific event handler

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事件处理程序完好无损?

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);

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 same object, 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. 由于jQuery的1.7,该方法.on.off是添加和移除事件处理程序的首选方式。 For this purpose they behave exactly like .bind and .unbind and also work with namespaced events. 为此,它们的行为与.bind.unbind完全相同,并且还可以使用命名空间事件。

jQuery allows you to bind events that will be unbound after their first invocation. jQuery允许您绑定在第一次调用后将被解除绑定的事件。 If you are looking to only run this keyup function once, look at the .one() method listed here: http://api.jquery.com/one/ 如果您只想运行此keyup函数一次,请查看此处列出的.one()方法: http//api.jquery.com/one/

$(document).one('keyup', function(e) {
              if (e.keyCode == 27) { functionZzy(); }
});

If you only have one handler on an element, you can safely unbind it using unbind without using named functions as Nick Craver suggests. 如果你在一个元素上只有一个处理程序,你可以使用unbind安全地取消绑定它,而不使用Nick Craver建议的命名函数。 In this case, calling 在这种情况下,打电话

$('#Inputfield').unbind('keyup');

will not affect the handler on document . 不会影响document上的处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM