JavaScript window.opener的用法

来源:互联网 发布:unity3d增强现实 编辑:程序博客网 时间:2024/05/21 09:43

window.opener主要用于通过子页面操纵打开子页面的父页面。通过这种方法,子页面可以象操纵本页面一样操纵父页面。

通过Windows.opener可以获取父页面对象,接下来就可以象操纵本页面一样操纵父页面。这里重点列出几个特殊的方法:

window.opener.location.reload(): 该方法可以在子页面中刷新父页面。

window.opener.close():该方法在子页面中关闭父页面。

window.opener.document.operator:该方法就是子页面操纵父页面的方法,其中operator就是和本页面一样的具体操纵。Eg:

 window.opener.document.getElementById('testValue').value='111111' //在子页面中给id为testValue的元素赋值。

具体举例如下:

父页面opner.html


  1. <html>  
  2. <head>  
  3. <meta http-equiv="Content-Type" content="text/html; charset=gb2312">  
  4. <title>opner</title>  
  5. <mce:script type="text/javascript"><!--  
  6. function tetsVlaue(){  
  7.         document.getElementById('childTest').document.getElement('refreshParent').value="111111";  
  8. }  
  9. // --></mce:script>  
  10. </head>  
  11. <body>  
  12. <input type="button" value="open" onclick="window.open('child.html','childTest')" />  
  13. <br>  
  14. <input type="text" id="testValue" name="testValue" value="123" readonly />  
  15. <br>  
  16. <input type="button" value="testChild" onclick="testChild()">  
  17. </body>  
  18. </html>  
  19. 子页面child.html  
  20. <html>  
  21. <head>  
  22. <meta http-equiv="Content-Type" content="text/html; charset=gb2312">  
  23. <title>childTest</title>  
  24. </head>  
  25. <body>  
  26. <mce:script type="text/javascript"><!--  
  27. function refreshParent(){  
  28.   window.opener.location.reload();  
  29.   window.opener.document.getElementById('testValue').value='111111';  
  30. }  
  31.    
  32. function closeparent(){  
  33. window.opener.close();  
  34. }  
  35. // --></mce:script>  
  36. <input type="button" id="refreshParent" value="refreshParent" onclick="refreshParent()">  
  37. <br>  
  38. <input type="button" value="closeparent" onclick="closeparent()">  
  39.    
  40. </body>
  41. </html>  

 

该例实现在子页面child.html中关闭,从新加载父页面opener.html,同时为新页面相应元素赋值,注意父页面中文本框的变化。