1、準備工做javascript
新建一個頁面:parent.html,代碼以下:css
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>p</title> <link rel="stylesheet" href="css/main.css" /> </head> <body> <input type="button" id="open" value="打開子窗口" /> <input type="button" id="close" value="刷新當前而且關閉打開的子窗口" /> </body> <script type="text/javascript"> window.onload=function(){ var cc=document.getElementById("open"); var newwin; cc.onclick=function(){ newwin=window.open("child.html","child",'height=500, width=500, top=200,left=200, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no'); }; var ss=document.getElementById("close"); ss.onclick=function(){ window.location.href = window.location.href; newwin.close(); }; function call(){ alert(1); }; window.call=call; }; </script> </html>
新建一個頁面:child.html,代碼以下:html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>c</title> <link rel="stylesheet" href="css/main.css" /> </head> <body> <input type="button" id="close" value="關閉當前頁面" /> <a href="javascript:void(0)" onclick="refreshParent()">刷新父窗口並關閉當前窗口</a> <input type="button" id="call" value="調用父窗口方法" /> </body> <script type="text/javascript"> var cc=document.getElementById("close"); cc.onclick=function(){ window.close(); }; function refreshParent() { window.opener.location.href = window.opener.location.href; if (window.opener.progressWindow){ window.opener.progressWindow.close(); } window.close(); }; var pp=document.getElementById("call"); pp.onclick=function(){ window.opener.call(); }; </script> </html>
2、父頁面操做子頁面java
window.open(url,name,style)數據庫
利用上面的方法,咱們能夠打開一個指定的html頁面,第一個參數就是要打開的頁面地址;第二個是名字,自定義;第三個就是設置打開頁面的樣式和外觀。網站
咱們知道利用:ui
window.close()url
能夠關閉一個頁面,可是咱們當前的window指代parent這個頁面,咱們要關閉的是打開的頁面(child.html),其實在調用window.open()會返回打開的窗口對象,咱們只要定義變量接收就行了,這時候咱們的變量就表明了打開的子窗口spa
即變量 newwin 等於child.html頁面的windowcode
正常關閉是window.close(),這時候咱們的變量newwin表明的子窗口對象,只要
newwin.close()就關閉子頁面了,和window調用關閉方法同理。
父頁面還作了刷新處理,除了利用Location的href屬性的設置還能夠利用reload方法等。
3、子頁面操做父頁面
子頁面要對父頁面作處理,咱們目的很明確,要操做的對象也很明確,就是parent.html的window
咱們如何獲取parent頁面的window,咱們利用的就是
window.opener
window這裏表明的是child頁面,調用opener屬性就會獲取到parent頁面的window對象
window對象作爲全局對象,就是一個頁面的根,只要能獲取到頁面的window咱們就如同握住了頁面的小命,想怎麼作就能夠怎麼作。
此時咱們深深銘記 window.opener 就是父頁面
咱們此時調用 window.opener.close()就是關閉父頁面,
window.opener.location就是獲取父頁面的地址對象
window.opener.document就是獲取父頁面的整個文檔,等等等
總結:
其實這麼多介紹,咱們不少網站實際上是利用不到的,不過針對一些特殊的操做,上面的纔會被使用到
好比:
咱們打開的子頁面作了數據庫數據的操做,操做後咱們父頁面是對數據的顯示,因此須要子頁面操做時或者關閉時讓父頁面刷新,好能夠看到最新的數據變化。