繁体   English   中英

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

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

给定以下 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>

这将在页面上重复多次,当用户单击 .top div 中的链接时, .top将焦点设置在.bottom div 中的输入字段上?

我目前正在使用下面的 JQuery 代码使.bottom div 在单击时成功显示,但似乎无法弄清楚如何同时将焦点设置在输入字段上。

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

谢谢!

试试这个,将焦点设置到第一个输入字段:

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

贾斯汀的回答对我不起作用(铬 18,Firefox 43.0.1)。 jQuery 的.focus()创建视觉突出显示,但文本 cursor 不会出现在字段中(jquery 3.1.0)。

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();
}

如果输入恰好在引导模式对话框中,则答案会有所不同。 在显示后从如何设置焦点复制到引导模式中的第一个文本输入,这是必需的:

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

暂无
暂无

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

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