0
我在頁面上有多個文本框和多個按鈕。如果我在一個TextBox中時按下Enter鍵,則應該執行相應的Button單擊事件。用JavaScript查找多個按鈕中按下哪個按鈕
我寫了下面的代碼,但它不工作。任何人都可以請解釋我如何...
<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();
}
您是否需要通過輸入鍵訪問其他文本框才能按下'屬於'另一個文本框?如果沒有,您可以通過在頁面上製作多個表單來實現這種行爲。 – dougajmcdonald
我正在使用GridView來插入記錄。那一次,我無法使用你的技術,對吧? :)我想要JavaScript特定的解決方案。 –
在webforms中不能有多個表單。文本框控件需要在窗體控件中,並且只允許1個窗體控件 –