RegisterClientScriptBlock和RegisterStartupScript的区别

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.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8.     <script type="text/javascript">  
  9.         function GetValue() {  
  10.             var value = document.getElementById("test").value;  
  11.             alert(value);  
  12.         }  
  13.     </script>  
  14. </head>  
  15. <body>  
  16.     <form id="form1" runat="server">  
  17.     <div>  
  18.     <input type="text" value="value" id="test"/>  
  19.     </div>  
  20.     </form>  
  21. </body>  
  22. </html>  
  23. </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获取页面上的值是获取不到的。

posted on 2014-12-08 17:00  yzl495  阅读(249)  评论(0编辑  收藏  举报

导航