如何使用JQuery对输入字段进行集中设置?

时间:2022-12-06 15:57:59

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中的链接时,如何将焦点放在.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!

谢谢!

2 个解决方案

#1


103  

Try this, to set the focus to the first input field:

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

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

#2


6  

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).

贾斯汀的答案对我不起作用(铬18,火狐43.0.1)。jQuery的.focus()创建了可视化的高亮显示,但是文本光标并没有出现在字段中(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();
}

#1


103  

Try this, to set the focus to the first input field:

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

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

#2


6  

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).

贾斯汀的答案对我不起作用(铬18,火狐43.0.1)。jQuery的.focus()创建了可视化的高亮显示,但是文本光标并没有出现在字段中(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();
}