简体   繁体   English

如何解除特定键的事件绑定

[英]How to unbind events for specific keys

I'm suspecting that some jQuery plugins that I'm using are interfering with my keyboard arrow key presses by having specific events bound.我怀疑我正在使用的一些 jQuery 插件通过绑定特定事件来干扰我的键盘箭头键按下。

Assuming I don't care about breaking whatever it is they're doing, how can I unbind all events for, say, the left and right arrow key presses?假设我不在乎破坏他们正在做的任何事情,我怎么能解除所有事件的绑定,比如左右箭头键按下?

How would one debug or see a list of events that are fired upon key pressing?如何调试或查看按键触发的事件列表? (I don't know which lines of code are currently handling the key presses, if any) (我不知道哪些代码行当前正在处理按键操作,如果有的话)

You can unbind that without affecting other bound keypress events:您可以在不影响其他绑定按键事件的情况下解除绑定:

$(document).unbind("keypress.key37");
$(document).unbind("keypress.key39");

That's called namespaced events , ie labelling specific bindings using <event_name>.<namespace> (in your case, "keypress.key37 & keypress.key39").这称为命名空间事件,即使用<event_name>.<namespace>标记特定绑定(在您的情况下,“keypress.key37 & keypress.key39”)。

If the arrow keys are triggered when you are focused anywhere on the page, then the event handlers are probably bound to the window or document, unbind like so:如果当您将焦点放在页面上的任何位置时触发箭头键,则事件处理程序可能绑定到窗口或文档,如下所示解除绑定:

$(window).unbind('keydown');
$(document).unbind('keydown');

If you want to unbind the event ONLY for 'left' or 'right' arrow key, you can stop the event like so:如果您只想为“向左”或“向右”箭头键解除绑定事件,您可以像这样停止事件:

$(window).bind('keydown', function(e){
    switch(e.keyCode) {
        case 37: // left arrow
            e.preventDefault;
            e.stopPropagation;
            break;
        case 39: // right arrow
            e.preventDefault;
            e.stopPropagation;
            break;
    }
});

I would recommend debugging to find where these events are bound(or even if they're bound).我建议调试以找到这些事件的绑定位置(或者即使它们被绑定)。 If these are bound with jQuery, they will be viewable via .data();如果这些与 jQuery 绑定,它们将可以通过 .data() 看到;

eg, in a console:例如,在控制台中:

$('.suspected.element').data().events

If key events are truly the cause via some plugin, I would look to modify the binding of the events, rather than adding workarounds.如果关键事件确实是通过某个插件引起的,我会考虑修改事件的绑定,而不是添加解决方法。

function stopRKey(evt) {
      var evt = (evt) ? evt : ((event) ? event : null);
      var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement :null);
      if ((evt.keyCode == 13) && (node.type=="text"))  {return false;}
}
document.onkeypress = stopRKey;

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

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