方法一:
在JS中使用button按钮的click方法
<script type="text/javascript">
function JSFun2()
{
document.getElementById("<%= btnTest4.ClientID %>").click();
}
</script>
方法二:
ClientScript.GetPostBackEventReference(btnTest2, "")
上面这行代码的返回值是一个string,"__doPostBack('btnTest2','')".
然后使用RegisterClientScriptBlock注册一下脚本.
string jscript = "function JSFun1(){" + ClientScript.GetPostBackEventReference(btnTest2, "") + "};";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", jscript, true);
HTML
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="GetPostBackEventReference_Test._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function JSFun2()
{
document.getElementById("<%= btnTest4.ClientID %>").click();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="btnTest1" runat="server" Text="Test1" />
<asp:Button ID="btnTest2" runat="server" Text="Test2" OnClick="btnTest2_Click" />
<br />
<asp:Button ID="btnTest3" runat="server" Text="Test3" />
<asp:Button ID="btnTest4" runat="server" Text="Test4" OnClick="btnTest2_Click" />
</form>
</body>
</html>
C#
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace GetPostBackEventReference_Test
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.btnTest1.OnClientClick = "JavaScript:JSFun1();return false;";
this.btnTest3.OnClientClick = "JavaScript:JSFun2();return false;";
}
string jscript = "function JSFun1(){" + ClientScript.GetPostBackEventReference(btnTest2, "") + "};";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", jscript, true);
}
protected void btnTest2_Click(object sender, EventArgs e)
{
Response.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fffffff"));
}
}
}