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

Javascript
js返回当前网页的url
简明json介绍
JavaScript在IE中“意外地调用了方法或属性访问”
JS获得鼠标位置(兼容多浏览器ie,firefox)修正版
JavaScript 基础问答 四
支持多浏览器(IE、Firefox、Opera)剪切板复制函数
js 解决“options为空或不是对象”
走出JavaScript初学困境—js初学
JavaScript入门教程(6) Window窗口对象
JavaScript 快捷键设置实现代码
Extjs Ajax 乱码问题解决方案
JavaScript 实现模态对话框 源代码大全
[原创]js 日期加红代码 适用于各种cms
论坛里点击别人帖子下面的回复,回复标题变成“回复 24# 的帖子”
[原创]javascript 改变字体大小方法集合
javascript 单行文字向上跑马灯滚动显示
一个简单的javascript类定义例子
javascript 类定义的4种方法
javascript类继承机制的原理分析
firefox(火狐)和ie浏览器禁止右键和禁止复制的代码

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-10   浏览: 68 ::
收藏到网摘: 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>