jQuery: trigger keypress function on entire document but not inside inputs and textareas?

前端 未结 4 1738
无人共我
无人共我 2021-02-03 17:53

I have this …

$(document).keypress(function(e) {
        if ( e.keyCode === 119 ) // w
            doSomething();
    });

Wo when pressing \"w\

4条回答
  •  后悔当初
    2021-02-03 18:18

    If your event handler is bound to document, the event will have already been raised on the input element and bubbled up to the html element, so you will have to handle the exclusion within the code for the handler itself. The alternative is specifically binding a second handler for the input elements which prevents the event from bubbling, but that is probably not the right approach.

    Code demo

    $(function() {
        $(document).keypress(function(e) {
            if ($(e.target).is('input, textarea')) {
                return;   
            }
            if (e.which === 119) doSomething();
        });
    });​
    

    p.s. you can have a look at the jQuery event object documentation to see what properties it exposes.

提交回复
热议问题