如何使用 JQuery 在输入字段上设置焦点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6738760/
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 Focus on Input Field using JQuery
提问by rolling stone
Given the following HTML structure:
给定以下 HTML 结构:
<div class="wrapper">
<div class="top">
<a href="http://example.com" class="link">click here</a>
</div>
<div class="middle">
some text
</div>
<div class="bottom">
<form>
<input type="text" class="post">
<input type="submit">
</form>
</div>
<div>
which will be repeated several times on the page, how do I set the focus on the input field in the .bottom
div when a user clicks on the link in the .top
div?
这将在页面上重复多次,.bottom
当用户单击.top
div 中的链接时,如何将焦点设置在div 中的输入字段上?
I am currently making the .bottom
div appear successfully on click using the JQuery code below, but can't seem to figure out how to set focus on the input field at the same time.
我目前正在.bottom
使用下面的 JQuery 代码使div 在点击时成功显示,但似乎无法弄清楚如何同时将焦点设置在输入字段上。
$('.link').click(function() {
$(this).parent().siblings('div.bottom').show();
});
Thanks!
谢谢!
回答by Justin Ethier
Try this, to set the focus to the first input field:
试试这个,将焦点设置到第一个输入字段:
$(this).parent().siblings('div.bottom').find("input.post").focus();
回答by Kevin Buchs
If the input happens to be in a bootstrap modal dialog, the answer is different. Copying from How to Set focus to first text input in a bootstrap modal after shownthis is what is required:
如果输入恰好在引导模式对话框中,则答案不同。显示后从如何设置焦点复制到引导模式中的第一个文本输入,这是必需的:
$('#myModal').on('shown.bs.modal', function () {
$('#textareaID').focus();
})
回答by MKaama
Justin's answer did not work for me (Chromium 18, Firefox 43.0.1). jQuery's .focus()
creates visual highlight, but text cursor does not appear in the field (jquery 3.1.0).
贾斯汀的回答对我不起作用(Chromium 18,Firefox 43.0.1)。jQuery 的.focus()
创建视觉突出显示,但文本光标不会出现在字段中 (jquery 3.1.0)。
Inspired by https://www.sitepoint.com/jqueryhtml5-input-focus-cursor-positions/, I added autofocusattribute to the input field and voila!
受https://www.sitepoint.com/jqueryhtml5-input-focus-cursor-positions/ 的启发,我在输入字段中添加了autofocus属性,瞧!
function addfield() {
n=$('table tr').length;
$('table').append('<tr><td><input name=field'+n+' autofocus></td><td><input name=value'+n+'></td></tr>');
$('input[name="aa"'+n+']').focus();
}