您现在的位置: 365建站网 > 365文章 > Javascript怎么在两个窗体之间传值

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

文章来源:365jz.com     点击数:684    更新时间:2009-09-26 11:41   参与评论

原文:刘武|Javascript怎么在两个窗体之间传值  

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

如我们新建窗体FatherPage.htm:

XML-Code:

</>code

  1. <script type="text/javascript">
  2. function OpenChildWindow()
  3. {
  4.     window.open('ChildPage.htm');  
  5. }
  6. </script>
  7. <input type="text" id="txtInput" />
  8. <input type="button" value="OpenChild" onclick="OpenChildWindow()" />

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

XML-Code:

</>code

  1. <script type="text/javascript">
  2. function SetValue()
  3. {
  4.     window.opener.document.getElementById('txtInput').value
  5.         =document.getElementById('txtInput').value;
  6.     window.close();
  7. }
  8. </script>
  9. <input type="text" id="txtInput" />
  10. <input type="button" value="SetFather" onclick="SetValue()" />

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

XML-Code:

</>code

  1. <script type="text/javascript">
  2. function OpenChildWindow()
  3. {
  4.     var child = window.open('ChildPage.htm'); 
  5.     child.document.getElementById('txtInput').value
  6.         =document.getElementById('txtInput').value;
  7. }
  8. </script>
  9. <input type="text" id="txtInput" />
  10. <input type="button" value="OpenChild" onclick="OpenChildWindow()" />

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

XML-Code:

</>code

  1. <script type="text/javascript">
  2. var child
  3. function OpenChildWindow()
  4. {
  5.     if(!child)   
  6.         child = window.open('ChildPage.htm'); 
  7.      child.document.getElementById('txtInput').value
  8.             =document.getElementById('txtInput').value;
  9. }
  10. </script>
  11. <input type="text" id="txtInput" />
  12. <input type="button" value="OpenChild" onclick="OpenChildWindow()" />

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

XML-Code:

</>code

  1. <body onunload="Unload()">
  2. <script type="text/javascript">
  3. function SetValue()
  4. {
  5.     window.opener.document.getElementById('txtInput').value
  6.         =document.getElementById('txtInput').value;
  7.     window.close();
  8. }
  9. function Unload()
  10. {
  11.     window.opener.child=null;
  12. }
  13. </script>
  14. <input type="text" id="txtInput" />
  15. <input type="button" value="SetFather" onclick="SetValue()" />
  16. </body>

如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛

发表评论 (684人查看0条评论)
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
昵称:
最新评论
------分隔线----------------------------

快速入口

· 365软件
· 杰创官网
· 建站工具
· 网站大全

其它栏目

· 建站教程
· 365学习

业务咨询

· 技术支持
· 服务时间:9:00-18:00
365建站网二维码

Powered by 365建站网 RSS地图 HTML地图

copyright © 2013-2024 版权所有 鄂ICP备17013400号