按键事件(如果未输入) [英] Keypress event if NOT input

查看:106
本文介绍了按键事件(如果未输入)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站上有以下jQuery事件

I have the following jQuery events in my site

    $(window).keyup (function(event) {
        switch (event.keyCode) {
            case 68:  // Alt-N = next
                scroll ('next');
                break;
            case 65:  // Alt-P = prev
                scroll ('prev');
                break;

        }

});

});

 <script>
    $(document).keydown(function(e) {
    if(e.keyCode==68){
        window.location.href = "{PreviousPost}";
    }
    });
</script>

我正在使用窗口和文档,因为它们都可以工作并且搜索并不能使我发现功能上的区别.但是无论如何,我想知道的是在输入字段中时如何防止函数触发.因为它可以正常工作,但我不希望用户仅在按下键并且没有输入时才触发该事件.

I'm using window and document because they both work and searching didn't result in me finding out what the difference is in terms of functionality. But anyway, what I'm wondering is how to keep the functions from firing, when it's in an input field. Cause it works and everything, but I don't want the event to fire when the user is typing only when they press the keys and are ... not typing.

这似乎很简单,但我确实进行了搜索.继续给我其他问题的结果.

It seems simple, but I really searched. Kept giving me results from other issues.

推荐答案

在这种情况下:

if ($(e.target).closest("input")[0]) {
    return;
}

执行的操作是查看目标是否起源于或通过input元素,然后返回而没有执行任何操作.更多: closest | event.target 其他情况的逻辑如下:

What that does is see if the target originates in or passes through an input element and return without doing anything if so. More: closest | event.target Your logic for other cases would follow, e.g.:

$(document).keydown(function(e) {
    if ($(e.target).closest("input")[0]) {
        return;
    }
    if(e.keyCode==68){
        window.location.href = "{PreviousPost}";
    }
});

-如果您还想滤除select元素,则:$(e.target).closest("input, select")(以此类推,例如button元素).

N.B. - If you also want to filter out select elements, then: $(e.target).closest("input, select") (and so on, for instance for button elements).

这篇关于按键事件(如果未输入)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆