RegisterClientScriptBlock和RegisterStartupScript的区别

时间:2021-12-19 09:04:02

RegisterClientScriptBlock在 Page 对象的 元素的开始标记后立即发出客户端脚本,RegisterStartupScript则是在Page 对象的 元素的结束标记之前发出该脚本。如果你的脚本有与页面对象(doucument对象)进行交互的语句,则推荐使用RegisterStartupScript,反之如果要想客户端脚本尽可能早的执行,则可以使用RegisterClientScriptBlock和Response.Write。

我们新建一个default页面:

  1. <SPAN style="FONT-FAMILY: Microsoft YaHei"><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="Study._default" %>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <title></title>
  6. <script type="text/javascript">
  7. function GetValue() {
  8. var value = document.getElementById("test").value;
  9. alert(value);
  10. }
  11. </script>
  12. </head>
  13. <body>
  14. <form id="form1" runat="server">
  15. <div>
  16. <input type="text" value="value" id="test"/>
  17. </div>
  18. </form>
  19. </body>
  20. </html>
  21. </SPAN>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="Study._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></title>
<script type="text/javascript">
function GetValue() {
var value = document.getElementById("test").value;
alert(value);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" value="value" id="test"/>
</div>
</form>
</body>
</html>

然后我们在后台pageload事件里面注册下两个脚本:

  1. <SPAN style="FONT-FAMILY: Microsoft YaHei"> protected void Page_Load(object sender, EventArgs e)
  2. {
  3. if (!IsPostBack) {
  4. Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "msg", "<script>alert('RegisterClientScriptBlock')</script>");
  5. Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('RegisterStartupScript')</script>");
  6. }
  7. }</SPAN>
 protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "msg", "<script>alert('RegisterClientScriptBlock')</script>");
Page.ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert('RegisterStartupScript')</script>");
}
}

运行页面我们可以在下图清楚地看到两个脚本的注册位置,RegisterClientScriptBlock在<form>标签之后,而RegisterStartupScript在</form>标签之前。

RegisterClientScriptBlock和RegisterStartupScript的区别

所以假如我们在页面未加载完全之前使用RegisterClientScriptBlock获取页面上的值是获取不到的。