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!
p.s. 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 开发者_Go百科needs to return here.
It's really confusing me :(
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)
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
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) {
// ...
});
精彩评论