如何使用 JQuery 将焦点设置在页面的第一个 <select> 元素上?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5000475/
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 set the focus on the first <select> element of the page using JQuery?
提问by user605660
I would like to set the focus on the first element of the page using JQuery when the page is loaded. I could successfully set the focus for first element by using
我想在页面加载时使用 JQuery 将焦点设置在页面的第一个元素上。我可以通过使用成功地为第一个元素设置焦点
$(":input:visible:first").focus();
or
或者
$(':input:enabled:visible:first').focus();
according to jquery, set focus on the first enabled input or select or textarea on the page.
根据jquery,将焦点设置在页面上第一个启用的输入或选择或文本区域上。
I tried to use any of the below:
我尝试使用以下任何一种:
$('select:first').focus();
$("select").first().focus();
$(':visible:first').focus();
$('enabled:visible:first').focus();
or other variations I could think of, but have not succeeded.
或我能想到的其他变化,但没有成功。
Could anyone help me on this problem? I am a beginner to JQuery.
有人能帮我解决这个问题吗?我是 JQuery 的初学者。
I would like this function to work for all major browsers.
我希望此功能适用于所有主要浏览器。
Thank you very much!
非常感谢!
回答by David Conde
The problem is most likely to be that you are not running the code on after the DOM is loaded. Try this one:
问题很可能是在加载 DOM 后您没有运行代码。试试这个:
$(document).ready(function(){
$("select:first").focus();
});
That should work.
那应该工作。
EDIT:You can simplify the code a bit by using this:
编辑:您可以使用以下方法稍微简化代码:
$(function(){
$("select:first").focus();
})
If you use it that way, jQuery will trigger that function when the document's DOM is ready.
如果您这样使用它,jQuery 将在文档的 DOM 准备好时触发该函数。
回答by Adeel
You are calling on element that is not loaded in DOM
. Place your code in ready
function.
您正在调用未加载的元素DOM
。将您的代码放在ready
函数中。
jQuery(document).ready(function() {
$(":input:visible:first").focus();
});
jQuery(document).ready(function() {
$(":input:visible:first").focus();
});
UPDATE:
更新:
As seen in @David answer and comments, he is right.
正如@David 的回答和评论中所见,他是对的。
$(document).ready(function(){
$("select:first").focus();
});
but you have not correctly included jquery (as seen in comment). you have missed to insert httpbefore script src
.
但是您没有正确包含 jquery(如评论中所示)。您错过了在 script 之前插入httpsrc
。
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>