[英]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. ps里面所有的功能都是一个
switch
语句。
[edit] Hey guys n gals - I cannot return false;
[编辑]嘿家伙ñ女同胞们-我不能
return false;
because the element I need to type in is an <input>
text, so the keyboard still needs to return here. 因为我需要输入的元素是
<input>
文本,所以键盘仍然需要返回此处。
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: 如果您确实想将
keydown event handler
绑定到标记中的所有节点,除了#pinkElephant
之外,您需要这样做:
$(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. 最后一个代码段检查是否
#pinkElephant
本身或子节点,并阻止了传播和默认操作。 This is done by invoking $.contains()
help 这是通过调用
$.contains()
帮助来完成的
Here's an alternate way to do what you require by checking to see that the target element's id
isn't pinkElephant
. 这是通过检查目标元素的
id
是否不是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
. 我假设您不希望
pinkElephant
元素触发keydown
。
Place a handler on #pinkElephant
that stops propagation of the event. 在
#pinkElephant
上放置一个处理程序,以停止事件的传播。
$('#pinkElephant').bind('keydown',false);
Note that passing false
to .bind()
requires jQuery 1.4.3 or later. 请注意,将
false
传递到.bind()
需要jQuery 1.4.3或更高版本。
If you're using an older version, do this: 如果您使用的是旧版本,请执行以下操作:
$('#pinkElephant').bind('keydown',function(){return false;});
Try this instead: 尝试以下方法:
$(':not(#pinkElephant)').keydown(function(e) {
// ...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.