简体   繁体   English

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

[英]jquery how to set input focus on control

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. 我的HeaderContent中有我的脚本,但它不起作用,没有专注于加载。 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. 是的,我知道这也可以在服务器端完成,但我只是想变得更好,更熟悉jquery。 Thanks. 谢谢。

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

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. 如果您使用jQuery和标准ASP.NET JavaScript,那么'$'将不会映射到jQuery,而是映射到ASP.NET的JavaScript框架。 You may need to substitute $("#foo") for jQuery("#foo") . 您可能需要将$("#foo")替换为jQuery("#foo")

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! 并检查它是否有效!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM