我正在尝试将onkeydown属性添加到asp:textbox。由于某种原因,我的代码找不到登录视图中的文本框。
我做错了吗?
<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>
答案 0 :(得分:1)
您的代码正在尝试在客户端脚本中添加事件处理程序属性。这需要在服务器端代码块中进行。类似的东西:
<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>
或者,如果您有代码隐藏页面,请在PreRender事件中添加attribute.Add调用。
答案 1 :(得分:0)
在您的aspx文件中,添加将现有UserName和Password文本框绑定到名为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>
答案 2 :(得分:-1)
尝试以这种方式连接事件处理程序参数:
<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>