Keypress event if NOT input

让人想犯罪 __ 提交于 2020-01-30 06:47:25

问题


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.


回答1:


In the event:

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

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

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




回答2:


The event already contains the target object, so we can check it like this:

if($(event.target).is('input,select,button')) return;

We put the object event.target in $() to refere the DOM element. We can check the element's type or whatever we need (.hasClass() for example)



来源:https://stackoverflow.com/questions/17891902/keypress-event-if-not-input

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