jQuery:如何选择除输入和文本区域以外的所有元素? (禁用按键事件) [英] JQuery: How to select all elements except input and textarea? (to disable keydown event)
问题描述
我正在尝试在我的jQuery应用程序中禁用退格键,以便它不会导致浏览器返回页面.但是,如果输入或textarea元素是焦点,我不想禁用它,因为我希望退格键在那里可以正常工作.
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;
}
});
我不明白为什么:not()函数不起作用.有没有更好的方法可以做到这一点?
I do not understand why the :not() function is not working. Is there a better way I can do this?
请注意,如果我删除了:not()函数,它将正常工作.也就是说,它仅针对输入和textarea元素触发.
Note that if I remove the :not() function, it works properly. That is, it only fires for input and textarea elements.
根据接受的答案,这是有效的代码.我相信有更好的方法可以做到这一点.
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;
}
}
});
推荐答案
您的问题是keydown
事件从<input>
或<textarea>
元素冒泡到包含该元素的普通元素,从而触发该事件元素.
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.
您需要检查e.target
.
这篇关于jQuery:如何选择除输入和文本区域以外的所有元素? (禁用按键事件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!