本文實例講述了JavaScript子窗口調用父窗口變量和函數的方法。分享給大家供大家參考。具體如下:
示例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()">調用父頁面的方法</button>
<button onclick="modify()">更改父頁面中變量的值</button>
</body>
</html>
只要在變量和函數前面加opener就可以訪問指定資源了。
但是當父窗口被關閉時,再如此使用會報一個錯:"被調用的對象已與其客戶端斷開連接。"
示例2:子頁面是父頁面的一個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內的變量值
var str=document.getElementById('txt1').value; //獲得文本框內輸入的值
frame1.window.div1.innerHTML=str; //將值填入子頁面的一個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()">將文本框內值填充入子界面</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>
小發現:刷新父頁面時,其中的iframe也會隨之刷新;刷新iframe時,父頁面不會刷新。
希望本文所述對大家的JavaScript程序設計有所幫助。