在input或textarea字段中禁用jquery keypress

Bil*_*ill 6 jquery

我正试图在按下某个键时触发事件.它可以正常使用此代码:

$(document).keypress(function(e){ 
    switch(e.which){ 
            case 96:$("a.quicklinks").trigger('click'); 
            break; 
    } 
Run Code Online (Sandbox Code Playgroud)

但是,如果用户在表单字段中,我想禁用此行为.如何测试用户是否在表单字段中键入以执行此操作?谢谢.

Dar*_*rov 16

$(document).keypress(function(e) { 
    if ($(e.target).is('input, textarea')) {
        // event invoked from input or textarea
    }
    ...        
});
Run Code Online (Sandbox Code Playgroud)


Mar*_*rco 1

也许你可以设置一个全局变量

var disable_keyevents = false;
$('textarea,input')
    .focus(function() { disable_keyevents = true })
    .blur(function() { disable_keyevents = true; });
Run Code Online (Sandbox Code Playgroud)

那么你只需在切换之前检查 $(document).keypress 事件中的disable_keyevents 的值即可。