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

时间:2024-04-22 22:31:11 

如我们新建窗体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>
标签:窗体之间,传值
0
投稿

猜你喜欢

  • JS的Form表单转JSON格式的操作代码

    2023-07-02 05:24:03
  • python获取http请求响应头headers中的数据的示例

    2023-06-30 14:49:02
  • 浅谈Python浅拷贝、深拷贝及引用机制

    2023-01-03 10:28:23
  • 揭开HTML 5工作草稿的神秘面纱

    2008-02-13 08:25:00
  • Pytorch数据读取与预处理该如何实现

    2021-12-23 17:44:35
  • python 实现提取PPT中所有的文字

    2023-05-01 04:21:35
  • python操作链表的示例代码

    2023-08-08 23:55:41
  • Python OpenCV 直方图的计算与显示的方法示例

    2022-10-15 07:36:24
  • Pandas进行数据编码的十种方式总结

    2021-10-17 19:05:56
  • python中的一些类型转换函数小结

    2021-11-01 10:42:11
  • 详解JS几种变量交换方式以及性能分析对比

    2024-04-10 16:13:58
  • 教你用Python实现一个轮盘抽奖小游戏

    2021-11-04 23:49:03
  • HTML5硝烟弥漫

    2009-07-06 14:44:00
  • vue-router传参的4种方式超详细讲解

    2024-04-27 15:48:21
  • Python探索之实现一个简单的HTTP服务器

    2021-06-04 16:52:02
  • Asp 返回引用类型函数代码

    2011-03-10 10:44:00
  • js constructor的实际作用分析

    2024-02-25 01:41:31
  • 浅谈关于JS下大批量异步任务按顺序执行解决方案一点思考

    2024-05-22 10:41:23
  • python 爬取英雄联盟皮肤图片

    2021-08-10 10:16:06
  • python基础教程之面向对象的一些概念

    2022-12-01 09:51:52
  • asp之家 网络编程 m.aspxhome.com