找不到的asp:文本框在Javascript
-
25-09-2019 - |
题
我试图添加的onkeydown属性一个asp:文本框。出于某种原因,我的代码无法找到文本框是一个loginview内。
我做错什么了吗?
<script type="text/javascript">
window.onload = function() {
UserName.Attributes.Add("onKeyDown", "KeyDownHandler('" + btn.ClientID + "')");
Password.Attributes.Add("onKeyDown", "KeyDownHandler('" + btn.ClientID + "')");
}
function KeyDownHandler(btn)
{
if (event.keyCode == 13)
{
event.returnValue=false;
event.cancel = true;
document.getElementById(btn).click();
}
}
</script>
解决方案
您的代码试图在客户端脚本中添加事件处理程序的属性。这需要在服务器端代码块的情况发生。是这样的:
<script runat="server">
UserName.Attributes.Add("onKeyDown", "KeyDownHandler('" + btn.ClientID + "')");
Password.Attributes.Add("onKeyDown", "KeyDownHandler('" + btn.ClientID + "')");
</script>
<script type="text/javascript">
function KeyDownHandler(btn)
{
if (event.keyCode == 13)
{
event.returnValue=false;
event.cancel = true;
document.getElementById(btn).click();
}
}
</script>
另外,如果你有一个代码隐藏页,把attribute.Add在PreRender事件调用。
其他提示
在你的aspx文件,添加将现有的用户名和密码文本框绑定到名为KeyDownHandler客户端事件处理程序的服务器脚本:
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
TextBox userNameControl = FindControl("UserName") as TextBox;
TextBox passwordControl = FindControl("Password") as TextBox;
if (userNameControl != null)
userNameControl.Attributes.Add("onKeyDown", "KeyDownHandler(this)");
if (passwordControl != null)
passwordControl.Attributes.Add("onKeyDown", "KeyDownHandler(this)");
}
</script>
然后声明事件处理程序的客户端脚本:
<script type="text/javascript">
function KeyDownHandler(domButton)
{
if (event.keyCode == 13)
{
event.returnValue=false;
event.cancel = true;
domButton.click();
}
}
</script>
尝试布线事件处理程序参数是这样的:
<script type="text/javascript">
window.onload = function() {
UserName.Attributes.Add("onKeyDown", "KeyDownHandler(this)");
Password.Attributes.Add("onKeyDown", "KeyDownHandler(this)");
}
function KeyDownHandler(domButton)
{
if (event.keyCode == 13)
{
event.returnValue=false;
event.cancel = true;
domButton.click();
}
}
</script>
不隶属于 StackOverflow