我有一个包含许多文本输入的页面。由于多种原因,所有输入共享同一类。
现在我试图在输入聚焦时捕获 ESC 按钮,并在输入有值或没有值时发出警报。
现在这在逻辑上仅适用于第一个字段。在第一个字段之后,由于所有输入共享同一类,因此当我按 ESC 按钮时,它会为您提供第一个输入的值。
那么我怎么能说我正在谈论第二个、第五个或我按下 ESC 键的任何输入呢?
这是一个示例: http://jsfiddle.net/Y5e9W/
第一个输入工作正常,第二个输入工作正常想法;当你按 ESC 时,它会给你第一个的值。
I have a page with many text input's. All input's share the same class for many reasons.
Now I am trying to capture a the ESC button when an input is focused and alert if the input has value or not.
Now this logically works only for the first field. After the first field, since all input's share the same class, when I press ESC button it gives you the value of the very first input.
So how can I say that I'm talking for the second, fifth or whatever input I am pressing ESC on.
Here is an example: http://jsfiddle.net/Y5e9W/
The first input works fine, the second input thought; when you press ESC it gives you the values of the first.
发布评论
评论(2)
您应该能够将
keyup
事件绑定到您的类的元素,而不是document
。然后this
将引用具有焦点的元素:这是一个更新的小提琴。请注意,我使用了事件对象的
which
属性,jQuery 公开它来处理keyCode
和charCode
之间的浏览器差异。根据评论更新
如果您确实需要在
文档
级别处理此问题,则可以使用has
方法可将.gp
元素的选择范围缩小到具有焦点的元素:这里是 另一个小提琴。
You should be able to bind the
keyup
event to the elements with your class, rather than thedocument
. Thenthis
will refer to the element with focus:Here's an updated fiddle. Note that I've used the
which
property of the event object, which jQuery exposes to deal with browser differences betweenkeyCode
andcharCode
.Update based on comments
If you do need to handle this at the
document
level, you can use thehas
method to narrow down your selection of.gp
elements to the one which has focus:Here's another fiddle.
你可以这样做 -
它只会响应具有 'gp' 类的元素的
keyup
事件,然后你可以使用this
访问相关元素。演示 - http://jsfiddle.net/uqS72/2/
You could do -
Which will only respond to the
keyup
event of elements with the 'gp' class, you can then usethis
to access the relevant element.Demo - http://jsfiddle.net/uqS72/2/