Javascript 两个窗体之间传值实现代码

本文详细介绍了如何在JavaScript中使用window.open()函数创建子窗口,并通过window.opener实现父窗口向子窗口传递值。通过实例展示了动态赋值、控制子窗口数量和关闭后清理父窗口引用的方法。
摘要由CSDN通过智能技术生成

众所周知window.open() 函数可以用来打开一个新窗口,那么如何在子窗体中向父窗体传值呢,其实通过window.opener即可获取父窗体的引用。

如我们新建窗体FatherPage.htm:
XML-Code:

复制代码 代码如下:

<script type="text/javascript">
function OpenChildWindow()
{
window.open('ChildPage.htm');
}
</script>
<input type="text" id="txtInput" />
<input type="button" value="OpenChild" οnclick="OpenChildWindow()" />


然后在ChildPage.htm中即可通过window.opener来访问父窗体中的元素:
XML-Code:

复制代码 代码如下:


<script type="text/javascript">
function SetValue()
{
window.opener.document.getElementById('txtInput').value
=document.getElementById('txtInput').value;
window.close();
}
</script>
<input type="text" id="txtInput" />
<input type="button" value="SetFather" οnclick="SetValue()" />


其实在打开子窗体的同时,我们也可以对子窗体的元素进行赋值,因为window.open函数同样会返回一个子窗体的引用,因此FatherPage.htm可以修改为:
XML-Code:

复制代码 代码如下:


<script type="text/javascript">
function OpenChildWindow()
{
var child = window.open('ChildPage.htm');
child.document.getElementById('txtInput').value
=document.getElementById('txtInput').value;
}
</script>
<input type="text" id="txtInput" />
<input type="button" value="OpenChild" οnclick="OpenChildWindow()" />


通过判断子窗体的引用是否为空,我们还可以控制使其只能打开一个子窗体:
XML-Code:

复制代码 代码如下:


<script type="text/javascript">
var child
function OpenChildWindow()
{
if(!child)
child = window.open('ChildPage.htm');
child.document.getElementById('txtInput').value
=document.getElementById('txtInput').value;
}
</script>
<input type="text" id="txtInput" />
<input type="button" value="OpenChild" οnclick="OpenChildWindow()" />


光这样还不够,当关闭子窗体时还必须对父窗体的child变量进行清空,否则打开子窗体后再关闭就无法再重新打开了:
XML-Code:

复制代码 代码如下:


<body οnunlοad="Unload()">
<script type="text/javascript">
function SetValue()
{
window.opener.document.getElementById('txtInput').value
=document.getElementById('txtInput').value;
window.close();
}
function Unload()
{
window.opener.child=null;
}
</script>
<input type="text" id="txtInput" />
<input type="button" value="SetFather" οnclick="SetValue()" />
</body>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白的编程日志

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值