jQuery jquery如何将输入焦点设置在控件上

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4652248/
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-08-26 17:38:17  来源:igfitidea点击:

jquery how to set input focus on control

jqueryasp.netinput

提问by user516883

Hey I am very new to jquery using asp.net, and I was wondering how to set focus on a textbox using jquery.

嘿,我对使用 asp.net 的 jquery 非常陌生,我想知道如何使用 jquery 将焦点设置在文本框上。

I have my script in my HeaderContent but it is not working, no focus on load. And yes I know this can be done on the server side as well, but I am just trying to get better and more familiar with jquery. Thanks.

我的 HeaderContent 中有我的脚本,但它不起作用,没有关注负载。是的,我知道这也可以在服务器端完成,但我只是想变得更好,更熟悉 jquery。谢谢。

<script type="text/javascript">
   $(document).ready(function () {
      $("#MainContent_LoginUser_UserName").focus();
   });
</script>

采纳答案by Nathan Taylor

Your code is correct. If it is failing, chances are $("#MainContent_LoginUser_UserName")is not the correct selector value or perhaps jQuery is not correctly loaded.

你的代码是正确的。如果失败,可能$("#MainContent_LoginUser_UserName")不是正确的选择器值,或者 jQuery 没有正确加载。

If you are using jQuery alongside standard ASP.NET JavaScript, then the '$' will not be mapped to jQuery, but instead to ASP.NET's JavaScript framework. You may need to substitute $("#foo")for jQuery("#foo").

如果您将 jQuery 与标准 ASP.NET JavaScript 一起使用,则“$”不会映射到 jQuery,而是映射到 ASP.NET 的 JavaScript 框架。您可能需要替换$("#foo")jQuery("#foo")

回答by Tiago Deliberali Santos

if your MainContent_LoginUser_UserName text box is a server side control, it will not work, because the id of the control will be different, thanks to the unique id asp.net associated with your server site controllers.

如果您的 MainContent_LoginUser_UserName 文本框是服务器端控件,它将不起作用,因为控件的 id 将不同,这要归功于与您的服务器站点控制器关联的唯一 id asp.net。

Try to change to this line:

尝试更改为这一行:

$("[id$=MainContent_LoginUser_UserName]").focus();

and check if it works!

并检查它是否有效!