客户端按键处理事件、设置焦点功能、__doPostBack ASP.NET

Client side keypress handling event, set focus function, and __doPostBack ASP.NET

本文关键字:doPostBack ASP NET 功能 设置 处理事件 客户端 焦点      更新时间:2023-09-26

我正在尝试执行以下操作:

  • 首先,文本框将重点放在页面加载上(这里没有问题)

  • 然后,当在该文本框内按下ENTER按钮时,它会将焦点切换到第二个文本框。

  • 最后,当在第二个文本框中按下ENTER时,它会执行回发并在事件后面重新编写代码,就像按经典<asp:button />

基于:

文本框的回车键按键时发生火灾事件

JavaScript 将焦点设置为 HTML 表单元素

我设法想出了:

.HTML:

 <asp:TextBox ID="txtNNoSerie" runat="server"  Width="150px" ClientIDMode="Static" onkeypress="EnterEventFirst(event)" AutoPostBack="false"></asp:TextBox>             
 <asp:TextBox ID="txtNNoIdentification" runat="server" Width="150px" ClientIDMode="Static" onkeypress="EnterEventSecond(event)" AutoPostBack="false"></asp:TextBox>
 <asp:Button id="btnAjouter" CssClass="ms-Button ms-Button--primary" onclick="btnAjouter_click" Text="+" ForeColor="White" runat="server"  Width="30px" />
    <input type="text" id="txtTest" /> <%-- Just for tests --%>

.JS:

  function EnterEventFirst(e) {
      if (e.keyCode == 13) {
          document.getElementById('txtTest').value = 'got it';
          document.getElementById('<%=txtNNoIdentification.ClientID%>').focus();
      }
  } 

  function EnterEventSecond(e) {
      if (e.keyCode == 13) {
          document.getElementById('txtTest').value = 'Again';
          __doPostBack('<%=btnAjouter.ClientID%>', "");
      }
  }

代码隐藏:

    protected void btnAjouter_click(object sender, EventArgs e)
    {
    }

JavaScript 函数被达到,因为我可以在测试文本框中看到"得到了它"和"再次",但只是半秒钟,然后它消失了......__DoPostBack功能不起作用。

看起来当您在文本框中按回车键时,它会自动执行无用的回发和页面重新加载......这就是我被困的地方

使用 ClientID 而不是 UniqueID。

好吧,文本框在按下回车键时自动回发,那好吧。

我在服务器端做了这一切,我讨厌这个,但我别无选择:

        txtNNoSerie.Focus();
        if (txtNNoSerie.Text != "")
            txtNNoIdentification.Focus();
        if (txtNNoSerie.Text != "" && txtNNoIdentification.Text != "")
            btnAjouter_click(this, new EventArgs());

服务器端代码...如果有人可以向我展示一些有效的客户端代码,我会接受它......