我在页面上有多个TextBox和多个按钮。如果我在一个TextBox中按Enter键,则应执行相应的Button click事件。
我已编写如下代码,但它无效。任何人都可以向我解释一下......
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<br />
<br />
<br />
<br />
<br />
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" />
<br />
<br />
<br />
<br />
<br />
<br />
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:Button ID="Button3" runat="server" Text="Button" OnClick="Button3_Click" />
<br />
<br />
<br />
<br />
<br />
<br />
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
<asp:Button ID="Button4" runat="server" Text="Button" OnClick="Button4_Click" />
</div>
代码
public partial class JavaScriptEnterKey : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Attributes.Add("OnKeyDown", "HitButton('" + Button1.ClientID + "');");
TextBox2.Attributes.Add("OnKeyDown", "HitButton('" + Button2.ClientID + "');");
TextBox3.Attributes.Add("OnKeyDown", "HitButton('" + Button3.ClientID + "');");
TextBox4.Attributes.Add("OnKeyDown", "HitButton('" + Button4.ClientID + "');");
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("Button1 is clicked");
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Write("Button2 is clicked");
}
protected void Button3_Click(object sender, EventArgs e)
{
Response.Write("Button3 is clicked");
}
protected void Button4_Click(object sender, EventArgs e)
{
Response.Write("Button4 is clicked");
}
}
**JavaScript**
function HitButton(Button) {
if (event.keyCode == 13) document.getElementById(Button).click();
}
答案 0 :(得分:0)
尝试使用按键事件而不是键码。这似乎适用于我的代码。