简体   繁体   English

在页面加载时将焦点设置在文本框上

[英]Setting focus on a text box on page load

I have already tried the information in How do you automatically set the focus to a textbox when a web page loads? 我已经尝试过如何在网页加载时自动将焦点设置为文本框中的信息?

 <asp:TextBox ID="tbSearchLastName" runat="server" style="float:right" CssClass="search" tabindex="1" meta:resourcekey="tbSearchLastNameResource" />

                        <script type="text/javascript">
                            window.onload = function () {
                                document.getElementById("tbSearchLastName").focus();
                            };
                        </script>

I want the page focus to be on the textbox when the page loads but I am getting the error: 我希望页面加载时页面焦点位于文本框上,但我收到错误:

"Unable to get value of the property 'focus': object is null or undefined" “无法获得属性'焦点'的值:对象为null或未定义”

Thanks. 谢谢。

你必须这样做......

document.getElementById('<%= tbSearchLastName.ClientID%>').focus();

The ID you give your TextBox (or any .NET control, for that matter) is not the same ID that gets rendered in the HTML. 您为TextBox(或任何.NET控件)提供的ID与在HTML中呈现的ID不同。 To get the correct ID, you need to do: 要获得正确的ID,您需要执行以下操作:

 document.getElementById("<%=tbSearchLastName.ClientID %>")

Or, if you are in .NET 4, you can force it to keep the same ID 或者,如果您使用的是.NET 4,则可以强制它保持相同的ID

 <asp:TextBox ID="tbSearchLastName" ClientIDMode="Static" runat="server"/>

check in source of your page (in browser) what is the real id of tbSearchLastName. 检查页面的来源(在浏览器中)tbSearchLastName的真实ID是什么。 Probably it is not loaded or has been changed 可能它没有加载或已被更改

Why don't you just put tbSearchLastName.Focus() in the code behind in the page_load method? 为什么不把tbSearchLastName.Focus()放在page_load方法后面的代码中?

http://msdn.microsoft.com/en-us/library/system.web.ui.control.focus.aspx http://msdn.microsoft.com/en-us/library/system.web.ui.control.focus.aspx

protected void Page_Load(object sender, EventArgs e)
{
    Form.DefaultFocus = "tbSearchLastName";
}
protected void Page_Load(object sender,EventArgs e){
tbSearchLastName.focus();
}

you can try this on aspx.cs file ,its simple and elegant 你可以在aspx.cs文件上试试这个,它简单而优雅

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

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