RegisterClientScriptBlock在 Page 对象的 元素的开始标记后立即发出客户端脚本,RegisterStartupScript则是在Page 对象的 元素的结束标记之前发出该脚本。如果你的脚本有与页面对象(doucument对象)进行交互的语句,则推荐使用RegisterStartupScript,反之如果要想客户端脚本尽可能早的执行,则可以使用RegisterClientScriptBlock和Response.Write。
我们新建一个default页面:
[html] view plaincopyprint?
- <SPAN style="FONT-FAMILY: Microsoft YaHei"><%@ 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>
- </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事件里面注册下两个脚本:
[csharp] view
plaincopyprint?
- <SPAN style="FONT-FAMILY: Microsoft YaHei"> 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>");
- }
- }</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获取页面上的值是获取不到的。
时间: 2024-10-22 16:02:09