今天Insus.NET练习JavaScript,实现从父窗口打开一个子窗口,在子窗口处理一些结果之后,把结果赋值于父窗口的文本框内。可看效果:

子窗口给父窗口赋值_JavaScript

 

在站点创建两个aspx页面,一个是PageA.aspx另一个是PageB.aspx:

在PageA.aspx的<head>节点内,写Javascript脚本,脚本有两个方法,一个是打开子窗口,一个是为文本框设值的方法:


子窗口给父窗口赋值_opener_02子窗口给父窗口赋值_opener_03View Code


<script type="text/javascript">

function popUp(url) {
objSubWin = window.open(url, "Popup", "toolbar=no,scrollbars=no,location=no,statusbar=no,menubar=no,resizable=0,width=300,height=80");
objSubWin.focus();
}

function SetValue(val) {
var amount = document.getElementById('<% = TextBoxAmount.ClientID %>');
amount.value = val;
}

</script>


然后在<body>节点内,拉一个TextBox和一个Button:


子窗口给父窗口赋值_opener_02子窗口给父窗口赋值_opener_03View Code


Amount:
<asp:TextBox ID="TextBoxAmount" runat="server" Enabled="false"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Call child window" OnClientClick="popUp('PageB.aspx')" />


OK,父页完成,接下来写PageB.aspx子页,还是先写Javascript脚本,也有两个函数,一个是验证文本框只能输入数字,另一个是计算方法,在calc()方法内,有呼叫到父窗口的方法。


子窗口给父窗口赋值_opener_02子窗口给父窗口赋值_opener_03View Code


<script type="text/javascript">
function isNumeric(keyCode) {
return ((keyCode >= 48 && keyCode <= 57) || keyCode == 8)
}

function calc() {
if (window.opener != null && !window.opener.closed) {
var qty = document.getElementById('<% = TextBoxqty.ClientID %>');
var price = document.getElementById('<% = TextBoxPrice.ClientID %>');

window.opener.SetValue(parseInt(qty.value) * parseInt(price.value));
}
}
</script>


在PageB.aspx的<body>节点内,拉两个文本框,一个Button铵钮。


子窗口给父窗口赋值_opener_02子窗口给父窗口赋值_opener_03View Code


数量<asp:TextBox ID="TextBoxqty" runat="server" onkeydown="return isNumeric(event.keyCode);" onpaste="return false;" Width="50"></asp:TextBox>
* 单价<asp:TextBox ID="TextBoxPrice" runat="server" onkeydown="return isNumeric(event.keyCode);" onpaste="return false;" Width="50"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Calculate" OnClientClick="calc()" />