简体   繁体   中英

A quick question about keypress and jQuery

$(document).keydown(function(e) {

Well, that's my code - I was wondering if it is possible to have something like:

$(document).not('#pinkElephant').keydown(function(e) {

(Except, that doesn't work...)

Any Ideas?

Thanks very much!

ps All that function has inside it, is a switch statement.

[edit] Hey guys n gals - I cannot return false; because the element I need to type in is an <input> text, so the keyboard still needs to return here.

It's really confusing me :(

If you really want to bind a keydown event handler to all nodes in your markup, with the exception of #pinkElephant you need to do it like this:

$(document).find('*').not('#pinkElephant').keydown(function() ..

or short

$(':not(#pinkElephant').keydown(function() ...

which implicitly uses the universal selector * .

Note, that this is never ever any good in terms of performance. I don't know your markup but I hope it's not very crouded using that kind of selector.

update

inspired by a comment, you could also do it like:

$(document).click(function(event) {
    if( event.target.id === 'pinkElephant' || $.contains($('#pinkElephant')[0], event.target) )
        return false;

    // ...
});

Last snippet checks whether #pinkElephant itself or a child node was clicked and prevents the propagation + the default action. This is done by invoking $.contains() help

Here's an alternate way to do what you require by checking to see that the target element's id isn't pinkElephant . Since this doesn't use the universal selector '*' it should perform better:

$(document).keydown(function(e) {
    if (e.target.id !== "pinkElephant") {
        alert("I'm not pink!");
    }
});

Here's a working example.

(updated from comment)

I assume you don't want elements inside pinkElephant to trigger the keydown .

Place a handler on #pinkElephant that stops propagation of the event.

$('#pinkElephant').bind('keydown',false);

Note that passing false to .bind() requires jQuery 1.4.3 or later.

If you're using an older version, do this:

$('#pinkElephant').bind('keydown',function(){return false;});

Try this instead:

$(':not(#pinkElephant)').keydown(function(e) { 
    // ...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM