javascript 在表单加载时在文本框上设置焦点()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18213385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:05:18  来源:igfitidea点击:

set focus() on textbox on form onload

javascriptjqueryhtml

提问by user2675939

I am trying to set focus on a textbox in a form that's a part of jQuery tree. Here is my code

我试图将焦点设置在作为 jQuery 树一部分的表单中的文本框上。这是我的代码

$(document).ready(function() {

       $("#search").focus();

});

HTML:

HTML:

 <div>
     <form action="search" method="post" name="frmSearch>
          <label for="search">Search:</label>
        <input type="text" name="search" id="search" />
        <input type="submit" name="button" value="Search" />
    </form>
</div>

When I click on Search tab in the tree, it won't set focus on the textbox. Can someone let me know what's wrong in the code?

当我单击树中的“搜索”选项卡时,它不会将焦点设置在文本框上。有人可以让我知道代码中有什么问题吗?

回答by cfs

You're focusing the textbox on page load, however as soon as you click anywhere else on the page (such as a tab), the focus will be removed from the textbox and given to whatever you just clicked.

您将文本框的焦点放在页面加载上,但是一旦您单击页面上的任何其他位置(例如选项卡),焦点将从文本框中移除并提供给您刚刚单击的任何内容。

Instead of focusing on page load, attach a click listener to your tab so that when it is clicked the searchtextbox gets focus. Since I haven't seen all your markup, I'm using #mySearchTabas a placeholder for the ID of your search tab:

不要关注页面加载,而是将点击侦听器附加到您的选项卡,以便在点击时search文本框获得焦点。由于我还没有看到您的所有标记,因此我将其#mySearchTab用作搜索选项卡 ID 的占位符:

$(document).ready(function() {
    $("#mySearchTab").on('click', function() {
       $('#search').focus();
    });
});

Also, don't forget to close your functions with a ).

另外,不要忘记用).

I'm not sure what your tree looks like but here's a working demousing jQuery tabs.

我不确定你的树是什么样子,但这里有一个使用 jQuery 选项卡的工作演示

回答by maverickosama92

try following:

尝试以下:

$(function(){
    $("input:first:text").focus();       
});

working fiddle here: http://jsfiddle.net/8CTqN/2/

在这里工作小提琴:http: //jsfiddle.net/8CTqN/2/

tested on chrome

在铬上测试

回答by Ali ?ar?k??o?lu

I made some modification in your js codes

我对你的 js 代码做了一些修改

http://jsfiddle.net/8CTqN/5

http://jsfiddle.net/8CTqN/5

$(document).ready(function(){
    $(function(){
        $("#search2").focus();      
    });
});