加入收藏 | 设为首页 | 会员中心 | 我要投稿 核心网 (https://www.hxwgxz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 创业 > 正文

Javascript怎么在两个窗体之间传值

发布时间:2018-08-13 16:57:17 所属栏目:创业 来源:站长网
导读:众所周知window.open() 函数可以用来打开一个新窗口,那么如何在子窗体中向父窗体传值呢,其实通过window.opener即可获取父窗体的引用。 如我们新建窗体FatherPage.htm: XML-Code: script type=text/javascriptfunction OpenChildWindow(){ window.open('C

众所周知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 childfunction 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>

(编辑:核心网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读