javascript 在页面加载时将焦点设置在文本框上
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7349682/
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
Setting focus on a text box on page load
提问by joncodo
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"
“无法获得属性‘焦点’的值:对象为空或未定义”
Thanks.
谢谢。
回答by Muhammad Akhtar
You have to do like...
你必须像...
document.getElementById('<%= tbSearchLastName.ClientID%>').focus();
回答by Matt
The ID you give your TextBox (or any .NET control, for that matter) is not the same ID that gets rendered in the HTML. To get the correct ID, you need to do:
您为 TextBox(或任何 .NET 控件,就此而言)提供的 ID 与在 HTML 中呈现的 ID 不同。要获得正确的 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"/>
回答by i100
check in source of your page (in browser) what is the real id of tbSearchLastName. Probably it is not loaded or has been changed
检查页面的源代码(在浏览器中)什么是 tbSearchLastName 的真实 ID。可能它没有加载或已被更改
回答by Justin
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
回答by Christian
protected void Page_Load(object sender, EventArgs e)
{
Form.DefaultFocus = "tbSearchLastName";
}
回答by Mac D'zen
protected void Page_Load(object sender,EventArgs e){
tbSearchLastName.focus();
}
you can try this on aspx.cs file ,its simple and elegant
你可以在 aspx.cs 文件上试试这个,它简单而优雅