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

126

给定以下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的链接时,页面上会重复多次出现.bottom div中的输入框。我已经成功使用以下JQuery代码使.bottom div成功显示在单击时,但似乎无法同时设置输入字段的焦点。

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

谢谢!


你的问题已经得到解答,但是:我假设你在事件回调函数的结尾处也执行了 return false; 或者 function(e) { e.preventDefault(); ..... } 吗?如果没有,在执行回调函数后,你的浏览器将会导航到那个页面。 - simshaun
@simshaun 导航到哪个页面? - rolling stone
好的,在你的例子中,当你点击那个链接时,它会跳转到http://example.com。 - simshaun
哦,没错,谢谢你提醒! - rolling stone
4个回答

159

尝试使用以下代码,将焦点设置到第一个输入框:

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

1
input:first之间需要加空格吗?jQuery会自动处理吗?我一直认为应该写成input:first - simshaun
是的,你可以用任何一种方式来编写它。我想 input:first 可能是更正式的写法,尽管另一种方式似乎更容易阅读。但也许这只是我的个人看法 :) - Justin Ethier
我猜是因为我已经习惯了,所以当我看到空格时,我自动想到“子元素”,需要一秒钟的时间来消除困惑。但是嘿,那只是我个人的想法。这种方式也很不错。 - simshaun
@justin 我实际上需要稍微调整一下才能使其正常工作:$(this).parent().siblings('div.bottom').find("input.post").focus(); 但是 .find() 是我要找的选择器。有趣的是, input :firstinput:first 都不起作用。 - rolling stone
jQuery的.focus()函数用于为输入框获取焦点时发出的事件添加处理程序。这不会设置输入框的焦点。被踩了。 - Kevin Buchs
显示剩余2条评论

26

太好了!正是我需要的,我已经调试了几个小时,尝试了延迟和各种技巧... :-) - Kim Lundberg Stegenborg Madsen
还有,不要忘记将此放在document.ready或类似于此(表单加载事件)的位置下。 - Baz Guvenkaya

8

Justin的答案对我不起作用(Chromium 18,Firefox 43.0.1)。jQuery的.focus()会创建视觉效果,但光标不会出现在字段中(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();
}

1
对我来说有效。更简单的版本是这样的: $('.class input').focus(); $('.class input').prop('autofocus'); - ejntaylor

2
//$GLOBALS['sitename'] is our domain site URL
//$_GET['s'] is the search parameter of our search, and we want to highlight that term searched...    
jQuery(document).ready(function($){  
        let loc=location.href;
        switch(loc) 
        {

    case "<?php echo $GLOBALS['sitename'] ?>?s=<?php echo $_GET['s'] ?>":       
        {       
        let searchf= $("form.search-form").find("input[type='search']:first");
//searchf.val('').focus();      
//empty the value to allow a new search and focus on the field....this works but better to highlight the searched term to allow the user to decide if want to type in something else or just hit again search. In case we want to empty the searched term 
           setTimeout(function (){
           searchf.delay(1000).focus().select(); 
           }, 1000);    
        break;
//.... end of relevant code 
        }

            

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接