简体   繁体   English

如何使用 JQuery 设置输入字段的焦点

[英]How to Set Focus on Input Field using JQuery

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?这将在页面上重复多次,当用户单击 .top div 中的链接时, .top将焦点设置在.bottom 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.我目前正在使用下面的 JQuery 代码使.bottom div 在单击时成功显示,但似乎无法弄清楚如何同时将焦点设置在输入字段上。

$('.link').click(function() {
    $(this).parent().siblings('div.bottom').show();
});

Thanks!谢谢!

Try this, to set the focus to the first input field:试试这个,将焦点设置到第一个输入字段:

$(this).parent().siblings('div.bottom').find("input.post").focus();

Justin's answer did not work for me (Chromium 18, Firefox 43.0.1).贾斯汀的回答对我不起作用(铬 18,Firefox 43.0.1)。 jQuery's .focus() creates visual highlight, but text cursor does not appear in the field (jquery 3.1.0). jQuery 的.focus()创建视觉突出显示,但文本 cursor 不会出现在字段中(jquery 3.1.0)。

Inspired by https://www.sitepoint.com/jqueryhtml5-input-focus-cursor-positions/ , I added autofocus attribute 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();
}

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 shown this is what is required: 在显示后从如何设置焦点复制到引导模式中的第一个文本输入,这是必需的:

$('#myModal').on('shown.bs.modal', function () {
  $('#textareaID').focus();
})  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM