[转]开新窗口中父子窗口传值研究
星期日, 01月 3rd, 2010打开一个新窗口,该子窗口调用父对象的方法或变量,这个问题一直没有搞清楚。网上找了些资料,总结一下:
打开新窗口一般有几种方法,window.open(…),window.showModalDialog(…),以及iframe中嵌套页面这里也一起研究吧,另外还有window.navigate(…)、window.location.href="…"、window.history.back(-1);都是实现同意页面内容跳转的,这里不讨论。
1、open子窗口:用window.opener代表父窗口的window对象
2、模态子窗口:间接通过传window对象到子窗口,然后子窗口可获得父窗口的window对象
3、iframe中子页面:用window.parent代表父窗口的window对象
父页面:1.htm 代码:
<html><head><title>打开父子窗口传值研究-父窗口</title> <script>var parValue="现在显示了父窗口中的变量值"; function test(){alert("现在显示了父窗口中的方法正常执行");}</script></head><body ><input type="button" id="mybutton1" value="打开open新窗口" onclick="window.open('2.htm');"><input type="button" id="mybutton2" value="打开modal窗口" onclick="window.showModalDialog('3.htm',window);" ><br><iframe id="subiframe" name="subiframe" src="4.htm" scrolling="auto" frameborder="1" ></iframe></body></html>
2.htm 代码:
<html><head><title>打开父子窗口传值研究-open打开子窗口</title><script>var buttonValue=window.opener.document.getElementById("mybutton2").value //获取父窗口中的对象 var parentValue=window.opener.parValue; //获取父窗口中的变量 function doParTest(){ window.opener.test(); //调用父窗口中的方法 }</script></head><body> <input type="button" value="open打开子窗口按钮" onclick="alert('buttonValue:'+buttonValue);alert('parentValue:'+parentValue);doParTest()"> </body></html>
3.htm 代码:
<html><head><title>打开父子窗口传值研究-打开modal子窗口</title><script>var parentWin=window.dialogArguments;var buttonValue=parentWin.document.getElementById("mybutton2").value; //获取父窗口中的对象 var parentValue=parentWin.parValue;//获取父窗口中的变量 function doParTest(){ parentWin.test(); //调用父窗口中的方法 }</script></head> <body bgcolor="#FFFFFF" text="#000000"> <input type="button" value="modal子窗口按钮" onclick="alert('buttonValue:'+buttonValue);alert ('parentValue:'+parentValue);parentWin.test();"></body></html>
4.htm 代码:
<html><head><title>打开父子窗口传值研究-iframe中子窗口</title><script>var buttonValue=window.parent.document.getElementById("mybutton2").value //获取父窗口中的对象 var parentValue=window.parent.parValue;//获取父窗口中的变量 function doParTest(){ window.parent.test(); //调用父窗口中的方法 }</script></head><body> <input type="button" value="iframe中子窗口按钮" onclick="alert('buttonValue:'+buttonValue);alert('parentValue:'+parentValue);doParTest()"> </body></html>
