JQuery: How to select all elements except input an

2019-04-30 04:10发布

问题:

I am trying to disable the backspace key in my jQuery app, so that it does not cause the browser to go back a page. However, I do not want to disable it if an input or textarea element is focused, because I want backspace to work properly there.

So, I want to select anything that is not an input or textarea.

Here is the code. The problem is that it fires for every element, even inputs and textareas.

    $(':not(input, textarea)').keydown(function(e) {
    if (e.keyCode === 8) {
        return false;
    }
});

I do not understand why the :not() function is not working. Is there a better way I can do this?

Note that if I remove the :not() function, it works properly. That is, it only fires for input and textarea elements.

EDIT: Based on the accepted answer, here is code that works. I am sure there is a better way to do this.

    $(document).keydown(function(e) {
    var element = e.target.nodeName.toLowerCase();
    if (element != 'input' && element != 'textarea') {
        if (e.keyCode === 8) {
            return false;
        }
    }
});

回答1:

Your problem is that the keydown event bubbles from the <input> or <textarea> element to the normal element that contains it, firing the event from that element.

You need to check e.target.



回答2:

try this code:

$("*:not(input)")