当前位置: 代码迷 >> ASP.NET >> 在aspx.CS 中执行 javascript 函数的有关问题
  详细解决方案

在aspx.CS 中执行 javascript 函数的有关问题

热度:4530   发布时间:2013-02-25 00:00:00.0
在aspx.CS 中执行 javascript 函数的问题

在aspx 前台中的 js 函数

HTML code
    <script type="text/javascript" language="javascript"><!--        var k = window.dialogArguments;        //获得父窗口传递来的值         //关闭窗口返回是否刷新的参数.         function winClose() {            //var s = document.getElementById("<%=txbChild_sendToFather.ClientID%>").value;            //我先把上面为变量 s 定义的代码注释掉,下面只为 s 赋了一个静态数字 100            var s = 100;            window.returnValue = s;            window.close();        }//-->         </script>


然后有两个按钮,分别是

HTML code
<input type ="button" value="关闭且返回值" onclick="winClose()" /><asp:Button  ID="Button1" runat="server" onclick="Button1_Click" Text="关闭且返回值" />


在aspx.CS 后台中,为 Button1 加上 Button1_Click

C# code
 protected void Button1_Click(object sender, EventArgs e)        {            this.Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), Guid.NewGuid().ToString(), "winClose();", true);        }


以上两个按钮,一个是htmlinput 一个是 服务器端 button ,均可以实现关闭且返回值,成功调用前台的 js winClose函数。


但是当我把前台的 js 函数变成这样

HTML code
<script type="text/javascript" language="javascript"><!--        var k = window.dialogArguments;        //获得父窗口传递来的值         //关闭窗口返回是否刷新的参数.         function winClose() {            //var s = 100;            //我把 var s 定义由静态数字 100 改为 取得 textbox 值            var s = document.getElementById("<%=txbChild_sendToFather.ClientID%>").value;            window.returnValue = s;            window.close();        }//-->         </script>


既把变量s 值由 100 变成了 var s = document.getElementById("<%=txbChild_sendToFather.ClientID%>").value;
以后,

则 Button1_Click 就执行不了 这段 js 函数了,就是提示 js 有错,

但是 <input type ="button" value="关闭且返回值" onclick="winClose()" />
这个 htmlinput 确可以正常执行这段 js函数


这是怎么回事呢,请大家帮忙 !!万分感激

------解决方案--------------------------------------------------------
另外,模式窗口缓存很很厉害,
 var k = window.showModalDialog("MainIframe.aspx?" + (new Date()).valueOf(), window, "dialogWidth:600px;status:no;dialogHeight:500px")

禁止缓存

另外,采用RegisterStartupScript,应该就没问题了。
注意服务器控件的id
k.document.getElementById("txbFather").value;
确保你的父窗口的txbFather这个id存在
------解决方案--------------------------------------------------------

你可以试试这样子
C# code
protected void Button1_Click(object sender, EventArgs e){        System.Text.StringBuilder cstext2 = new System.Text.StringBuilder();        cstext2.Append(string.Format("<script type=text/javascript>var s ='{0}'; ",txbChild_sendToFather.Text.ToString()));        cstext2.Append("window.returnValue = s;window.close();</");        cstext2.Append("script>");        Response.Write(string.Format("{0}",cstext2.ToString()));}
  相关解决方案