How to unbind a specific event handler

放肆的年华 提交于 2019-12-17 09:08:10

问题


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?


回答1:


You have to use a named function so you can reference that specific handler when calling .unbind(), like this:

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

Then later when unbinding:

$(document).unbind("keyup", keyUpFunc);



回答2:


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. For this purpose they behave exactly like .bind and .unbind and also work with namespaced events.




回答3:


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/

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



回答4:


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

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

will not affect the handler on document.



来源:https://stackoverflow.com/questions/3972886/how-to-unbind-a-specific-event-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!