ASP.NET相关事件及JS的执行顺序
实验代码:
ASPX:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Ajax.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script>
alert("head里自动执行的JS");
window.onload = show1;
function show1()
{
alert("window.onload");
}
function show()
{
alert("前台服务器按钮");
}
function show2()
{
alert("前台普通按钮");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="服务器按钮" OnClick="Button1_Click" OnClientClick="show()"/>
<input type="button" value="普通按钮" name="button" onclick="show2()"/>
</div>
</form>
<script>
alert("body里自动执行的JS");
</script>
</body>
</html>
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Ajax
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ClientScript.RegisterStartupScript(Page.GetType(), "", "alert('Page_Load事件')", true);
}
}
//protected void Page_Init(object sender, EventArgs e)
//{
// ClientScript.RegisterStartupScript(Page.GetType(), "", "alert('Page_Init事件')", true);
//}
//protected void Page_PreRender(object sender, EventArgs e)
//{
// ClientScript.RegisterStartupScript(Page.GetType(), "", "alert('Page_PreRender事件')", true);
//}
protected void Button1_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(Page.GetType(), "", "alert('后台服务器按钮')", true);
}
}
}
实验结论:
1.页面刚打开时的执行顺序:head里自动执行的JS==》Page_load事件==》body里自动执行的JS==》window.onload
2.点击服务器按钮时的执行顺序:前台服务器按钮==》head里自动执行的JS==》后台服务器按钮==》body里自动执行的JS==》window.onload
3.点击普通按钮时的执行顺序:前台普通按钮
4.Page_Init先于Page_Load先于Page_PreRender被执行
简单记录下,下次用到时,随时过来翻看。