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 />
<asp:Label ID="Label1" runat="server" Font-Size="Large"></asp:Label>
</div>
</form>
</body>
</html>
當你在瀏覽器中執行程式碼時,你將獲得如下輸出:
當你在輸入欄位中輸入文字時,它將觸發 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:TextBox 的 ontextchanged() 事件。