当前位置: 首页 > 图文教程 > 网络编程 > Javascript > Javascript 两个窗体之间传值实现代码

Javascript
一个简单的收缩菜单效果
HTML-CSS群中单选引发的“事件”
打开超链需要“确认”对话框的方法
用js实现网页上模仿桌面右键菜单
可以文本显示的公告栏的js代码
[原创]js与自动伸缩图片 自动缩小图片的多浏览器兼容的方法总结
极致之美:百行代码实现全新智能语言
表单(FORM)的一些实用效果代码
[原创]提供复制本站内容时出现,该文章转自等字样的js代码
javascript中巧用“闭包”实现程序的暂停执行功能
给网站上的广告“加速”显示的方法
[原创]jser必看的破解javascript各种加密的反向思维方法
用javascript代替marquee的滚动字幕效果代码
静态页面下用javascript操作ACCESS数据库(读增改删)的代码
[原创]由亿起发(eqifa.com)的页面发现顶部的http://16a.us/8.js想到的js解密
[原创]站长必须要知道的javascript广告代码
js defineSetter -给js的 "class"自动增加一个set的属性(方法)
Javascript & DHTML 实例编程(教程)(三)初级实例篇1—上传文件控件实例
WordPress 插件:CoolCode使用方法与下载
文档处理系列:随时更新

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-10   浏览: 72 ::
收藏到网摘: n/a

众所周知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" onclick="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" onclick="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" onclick="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" onclick="OpenChildWindow()" />

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

<body onunload="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" onclick="SetValue()" />
</body>