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

时间:2022-12-06 15:30:39

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>

2 个解决方案

#1


16  

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”)。

#2


7  

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!

并检查它是否有效!

#1


16  

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”)。

#2


7  

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!

并检查它是否有效!