window.parent针对iframe,window.opener针对window.open
父页面parent.jsp:
1 <%@ page language="java" contentType="text/html; charset=utf-8" 2 pageEncoding="utf-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 7 <title>Insert title here</title> 8 </head> 9 <script type="text/javascript"> 10 function openSubWin() 11 { 12 var _width = 300 ; 13 var _height = 200 ; 14 var _left = (screen.width - _width) / 2 ; 15 var _top = (screen.height - _height) / 2 ; 16 window.open("third.jsp",null, 17 "height=" + _height + ",width=" + _width + ",status=no,toolbar=no,menubar=no,location=no,resizable=yes,left=" + _left + ",top=" + _top); 18 } 19 </script> 20 21 <body> 22 <form name="form1"> 23 24 name:<input type="text" name="username" id="username" value="haohao" /> 25 <input type="button" value="弹出子页面" onClick="openSubWin();"> 26 27 </form> 28 <hr/> 29 <div> 30 <iframe src="child.jsp"></iframe> 31 </div> 32 33 </body> 34 </html>
子页面child.jsp:
1 <script type="text/javascript"> 2 3 function fun(){ 4 alert(window.parent.document.getElementById("username").value); 5 window.parent.document.getElementById("username").value="来自子页面的数据"; 6 } 7 </script> 8 </head> 9 <body> 10 <p style="color:red;">子页面</p> 11 <input type="button" value="dianji" onclick="fun()"/>
运行后界面:
点击子页面按钮“dianji” :
页面third.jsp:
1 <script type="text/javascript"> 2 function UpdateParent() 3 { 4 var _parentWin = window.opener ; 5 _parentWin.form1.username.value = "来自子窗口 的参数" ; 6 } 7 </script> 8 <input type="button" name="button" id="button" value="更新主页面的UserName内容" onClick="UpdateParent();">
点击按钮“更新主页面的UserName内容”改变parent.jsp页面的值
window.opener是当前页面A通过open方法弹出一个窗口B,那在B页面上 window.opener就是A
window.parent是当前页面C通过location.href转到新的页面D,那在D页面上window.parent就是C
或者是页面E里套一个frame为F,那F页面的window.parent就是E
如何页面A里套一个frame为B,B页面有个按钮,点击open一个页面C,那么在C页面window.opener.parent就是A