在C#中可以使用RegisterClientScriptBlock、RegisterStartupScript和RegisterClientScriptInclude来向客户端注册脚本,它们的区别是:
RegisterClientScriptBlock:在页面内容前注册脚本;
RegisterStartupScript:在页面内容后注册脚本;
RegisterClientScriptInclude:在页面内容前引用外部脚本;
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "a01", "<script>alert('a01');</script>");
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "a02", "alert('a02');",true);
Page.ClientScript.RegisterStartupScript(this.GetType(), "b01", "<script>alert('b01');</script>");
Page.ClientScript.RegisterStartupScript(this.GetType(), "b02", "alert('b02');", true);
Page.ClientScript.RegisterClientScriptInclude("c01", "http://www.mzwu.com/js/my.js");
}
显示结果为:
<!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><title>
无标题页
</title></head>
<body>
<form name="form1" method="post" action="Default.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTEzMjY3MzQ0M2RkeNhrlsakosMW4qcA4DhPw24uxyk=" />
</div>
<script>alert('a01');</script>
<script type="text/javascript">
<!--
alert('a02');// -->
</script>
<script src="http://www.mzwu.com/js/my.js" type="text/javascript"></script>
<div>
<span id="Label1">Hello World!</span>
</div>
<script>alert('b01');</script>
<script type="text/javascript">
<!--
alert('b02');// -->
</script>
</form>
</body>
</html>
说明
1.RegisterClientScriptBlock和RegisterStartupScript推荐使用RegisterStartupScript,特别是当注册的脚本要调用页面的元素或函数时,如果使用RegisterClientScriptBlock可能会发生元素/函数还没加载完毕导致出错。
2.使用发现如果页面缺少服务器端表单<form id="form1" runat="server"></form>会导致脚本注册不成功,也发现其实RegisterClientScriptBlock就是将脚本注册到<form id="form1" runat="server">后,RegisterStartupScript是将脚本注册到</form>前。