總結起來,在服務器控件中使用js的方法有如下幾種:
1.在<body>的onload中直接寫js.(如例1)
2.將服務器控件的事件代碼寫在html中,然後在控件的屬性中直接調用事件名稱.(如例1,3)
3.在Page_Load事件或服務器控件的事件中(如DataBound)設定服務器控件的Attribute(如例2)
1.将Js添加到服务器控件
例1:本示例通過onload屬性將js置於頁面的<body>中,單擊服務器button後,在button上顯示本地時間.
<%@ Page Language="C#" %>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
//單擊按鈕後會回發消息
//Response.Write("回发!");
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>使用 JavaScript</title></head>
<body onload="javascript:document.forms[0][''Button1''].value=Date();">
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="按钮"
OnClick="Button1_Click" Font-Bold="True" Font-Names="Verdana"
Font-Size="Larger" />
</div>
</form>
</body>
</html>
輸出的代碼:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>使用 JavaScript</title></head>
<body onload="javascript:document.forms[0][''Button1''].value=Date();">
<form name="form1" method="post" action="Default.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
value="/wEPDwUKMTY3NzE5MjIyMGRkVUxVdzEWBhD7U89t7JKIkQc6Cko=" />
</div>
<div>
<input type="submit" name="Button1" value="" id="Button1"
style="font-family:Verdana;font-size:Larger;font-weight:bold;" />
</div>
<div>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION"
value="/wEWAgK394SHCAKM54rGBtsX8d2S8MO7sf02DOAiquFyBkeY" />
</div></form>
</body>
</html>
例2:本示例通過在Page_Load事件中,將js添加到一個服務器button的Attribute上.
<%@ Page Language="C#" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Button1.Attributes.Add("onclick","javascript:alert(''多加注意!'')");
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>使用 JavaScript</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button id="Button1" runat="server" Font-Bold="True"
Font-Names="Verdana" Font-Size="Larger"
Text="单击我!"></asp:Button>
</div>
</form>
</body>
</html>
例3:本示在服務 |