器控件Attributes中直接調用事件,從而來使用js
<%@ Page Language="C#" %>
<script runat="server">
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
//Label1.Text = "回发!";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>使用 JavaScript</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>
<asp:ImageButton id="ImageButton1"
onmouseover="this.src=''button2.gif''"
onclick="ImageButton1_Click"
onmouseout="this.src=''button1.gif''" runat="server"
ImageUrl="button1.gif"></asp:ImageButton>
</p>
<p>
<asp:Label id="Label1" runat="server" />
</p>
</div>
</form>
</body>
</html>
2.使用大塊的js
--1.使用Page.ClientScript.RegisterStartupScript()
這個函數會將js代碼注冊在頁面的最後面,</form>的前面.
它的聲明如下:
RegisterStartupScript (type, key, script)
RegisterStartupScript (type, key, script, script tag specification)
例4:
在Page_Load事件添加如下代碼:
Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript",
"function AlertHello() { alert(''你好,ASP.NET''); }", true);
Button1.Attributes["onclick"] = "AlertHello()";
Button2.Attributes["onclick"] = "AlertHello()";
則生成後的代碼如下:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>使用 JavaScript</title>
</head>
<body>
<form name="form1" method="post" action="Default.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
value="/wEPDwUJMTM4ODA1MjE5D2QWAgIED2QWBAIBDw9kFgIeB29uY2xpY2s
FDEFsZXJ0SGVsbG8oKWQCAw8PZBYCHwAFDEFsZXJ0SGVsbG8oKWRk+DQIaJpw5
A7pyhzP8dxf/JGUSbA=" />
</div>
<div>
<input type="submit" name="Button1" value="Button"
onclick="AlertHello();" id="Button1" />
<input type="submit" name="Button2" value="Button"
onclick="AlertHello();" id="Button2" />
</div>
<div>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION"
value="/wEWAwK4yNWFBwKM54rGBgK7q7GGCHwBEr6DyGutQ/egvNrB3OYhCwM4" />
</div>
<script type="text/javascript">
<!--
function AlertHello() { alert(''你好,ASP.NET''); }// -->
</script>
</form>
</body>
</html>
--2.使用Page.ClientScript.RegisterClientScriptBlock()
這個函數會將js注冊在頁面的最前面,<form>的後面.如果js中調用了其它控件,將有可能出錯.
例5:
<%@ Page Language="C#" %>
<script runat="server& |