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

时间:2011-07-18 20:06:09

标签: jquery html

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

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

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

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

谢谢!

3 个答案:

答案 0 :(得分:119)

尝试此操作,将焦点设置为第一个输入字段:

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

答案 1 :(得分:7)

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

受到https://www.sitepoint.com/jqueryhtml5-input-focus-cursor-positions/的启发,我在输入字段中添加了自动对焦属性,瞧!

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

答案 2 :(得分:2)

如果输入恰好在引导模式对话框中,则答案是不同的。从How to Set focus to first text input in a bootstrap modal after shown复制,这是必需的:

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