這篇文章主要介紹了JavaScript子窗口調(diào)用父窗口變量和函數(shù)的方法,涉及JavaScript窗口調(diào)用的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
本文實(shí)例講述了JavaScript子窗口調(diào)用父窗口變量和函數(shù)的方法。分享給大家供大家參考。具體如下:
示例1:子窗口是新打開的窗口
父窗口:
- <!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>
- <title>parent</title>
- <script type="text/javascript">
- var parentPara='parent';
- function parentFunction() {
- alert(parentPara);
- }
- </script>
- </head>
- <body>
- <button onclick="parentFunction()">顯示變量值</button>
- <button onclick="window.open('child.html')">打開新窗口</button>
- </body>
- </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>
- <title>child</title>
- <script type="text/javascript">
- function modify() {
- opener.parentPara='child';
- }
- </script>
- </head>
- <body>
- <button onclick="opener.parentFunction()">調(diào)用父頁面的方法</button>
- <button onclick="modify()">更改父頁面中變量的值</button>
- </body>
- </html>
只要在變量和函數(shù)前面加opener就可以訪問指定資源了。
但是當(dāng)父窗口被關(guān)閉時(shí),再如此使用會(huì)報(bào)一個(gè)錯(cuò):"被調(diào)用的對(duì)象已與其客戶端斷開連接。"
示例2:子頁面是父頁面的一個(gè)iframe
父頁面:
- <!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>
- <title>parent</title>
- <script type="text/javascript">
- function fill() {
- //alert(frame1.window.childPara); //顯示frame1內(nèi)的變量值
- var str=document.getElementById('txt1').value; //獲得文本框內(nèi)輸入的值
- frame1.window.div1.innerHTML=str; //將值填入子頁面的一個(gè)div中
- }
- </script>
- </head>
- <body>
- <div style="background-color:yellow;width:300px;height:300px;">
- 父頁面
- <iframe id="frame1" src="child.html" frameborder="0" scrolling="no" width="120px" height="120px"></iframe>
- <br/><br/><br/><br/>
- <input id="txt1" type="text"/>
- <button onclick="fill()">將文本框內(nèi)值填充入子界面</button>
- </div>
- </body>
- </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>
- <title>child</title>
- <script type="text/javascript">
- function fun() {
- parent.fill();
- }
- </script>
- </head>
- <body>
- <div style="background-color:lightblue;width:100px;height:100px;">
- <b>子頁面</b><br/>
- <a href="#" onclick="fun()">同父頁面按鈕</a>
- <div id="div1" style="color:red;">
- </div>
- </div>
- </body>
- </html>
小發(fā)現(xiàn):刷新父頁面時(shí),其中的iframe也會(huì)隨之刷新;刷新iframe時(shí),父頁面不會(huì)刷新。
希望本文所述對(duì)大家的JavaScript程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選