HOWTO · JavaScript

通过 Javascript 触发 Asp:TextBox 的 ontextchanged 事件

如何通过 Javascript 触发 asp:TextBox 的 ontextchanged 事件?

好吧,如果你不想使用 Ajax 或其他任何东西来实现它并享受正常的 ASP.NET 回发,你可以这样做(不使用任何其他库):

在代码文件中,如果你使用的是 C# 和 .NET 2.0 或更高版本,请将以下接口添加到 Page 类中,如下所示:

public partial class Default : System.Web.UI.Page, IPostBackEventHandler {}

然后你需要将此函数添加到你的代码文件中。

public void RaisePostBackEvent(string eventArgument) {}

在 JavaScript 中的 onclick 事件中编写以下代码。

var pageId = '<%=  Page.ClientID %>';
__doPostBack(pageId, argumentString);

然后代码文件调用 RaisePostBackEvent 方法,并使用 eventArgument 参数作为 JavaScript 传递的 String 参数。你现在可以调用你想要的任何其他事件。

这是该问题的可能解决方案。

WebForm1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="textbox.WebForm1" %>

<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>

   <script type="text/javascript">
    function RefreshIt(selectObj) {
      __doPostBack('<%= Page.ClientID %>', selectObj.name);
    }
   </script>
<body>
  <form id="form1" runat="server">
  <div>
     <asp:TextBox runat="server" AutoPostBack="True" ID="txtG1" OnTextChanged="txtG1_TextChanged"
      onmouseout="javascript:RefreshIt(this);" ></asp:TextBox>
    <br />
    &nbsp;<asp:Label ID="Label1" runat="server" Font-Size="Large"></asp:Label>

  </div>
  </form>
</body>
</html>

当你在浏览器中运行代码时,你将获得如下输出:

通过 Javascript 触发 Asp:TextBox 的 Ontextchanged 事件

当你在输入字段中输入文本时,它将触发 ontextchange 事件并提供如下输出(即红色):

通过 Javascript 触发 Asp:TextBox 的 Ontextchanged 事件 - ontextchange 事件

你可以把 RefreshIt 函数改为 postback 作为一个参数。

你可能需要了解背后的代码并将 IPostBackEventHandler 添加到页面并处理 RaisePostBackEvent 函数。

WebForm1.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace textbox {
  public partial class WebForm1 : System.Web.UI.Page, IPostBackEventHandler {
    protected void Page_Load(object sender, EventArgs e) {}

    public void RaisePostBackEvent(string Arg) {
      if (txtG1.ID == Arg)
        txtG1_TextChanged(txtG1, null);
    }

    protected void txtG1_TextChanged(object sender, EventArgs e) {
      Label1.Text = txtG1.Text;
      Label1.ForeColor = System.Drawing.Color.Red;
      Label1.BackColor = System.Drawing.Color.White;
    }
  }
}

你可以使用下面提到的代码通过 JavaScript 触发 asp:TextBoxontextchanged() 事件。