jQuery 如何使用jQuery选择一个关注它的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/516152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select an element that has focus on it with jQuery
提问by jQuery Lover
How can you select an element that has current focus?
如何选择具有当前焦点的元素?
There is no :focus
filter in jQuery, that is why we can use something like this:
:focus
jQuery 中没有过滤器,这就是为什么我们可以使用这样的东西:
$('input:focus').someFunction();
采纳答案by Mike_G
Really the best way to do it is to setup a handler for the onFocus event, and then set a variable to the ID of the element that has focus.
最好的方法是为 onFocus 事件设置一个处理程序,然后将一个变量设置为具有焦点的元素的 ID。
something like this:
像这样:
var id;
$(":input").focus(function () {
id = this.id;
});
回答by Sam Shiles
$(document.activeElement)
will return the currently focused element and is faster than using the pseudo selector :focus.
$(document.activeElement)
将返回当前聚焦的元素,并且比使用伪选择器 :focus 更快。
回答by BiBi
alert($("*:focus").attr("id"));
I use jQuery.
我使用 jQuery。
It will alert id of element is focusing.
它将提醒元素的 id 正在聚焦。
I hope it useful for you.
我希望它对你有用。
回答by bendewey
Have you tried
你有没有尝试过
$.extend($.expr[':'], {
focused: function(elem) { return elem.hasFocus; }
});
alert($('input :focused').length);
回答by jmanrubia
If you use JQuery, you can write a selector like this:
$.expr[':'].focus = function(a){ return (a == document.activeElement); }
You can then select the currently focused element: $(":focus")
然后,您可以选择当前聚焦的元素: $(":focus")
Not only form controls can have focus. Any html element with a tabindex can be focused in modern browsers.
不仅表单控件可以有焦点。任何带有 tabindex 的 html 元素都可以在现代浏览器中聚焦。
回答by TurboHz
Lifted from the examples for the current jQuery version (1.7) docs:
摘自当前 jQuery 版本 (1.7) 文档的示例:
$(elem).is(":focus");
回答by Somnath Muluk
For checking element has focus or not.
用于检查元素是否具有焦点。
if ($("...").is(":focus")) {
...
}
回答by Hengjie
Here is the CoffeeScript version of it. Based upon jmanrubia's code:
这是它的 CoffeeScript 版本。基于 jmanrubia 的代码:
$.expr[':'].focus = (a) ->
a is document.activeElement
$.expr[':'].focus = (a) ->
a is document.activeElement
You would also call it like so $(".:focus")
你也可以这样称呼它 $(".:focus")