DIV CSS 佈局教程網

釐清 JavaScript 中 opener 與 parent 的差異
編輯:JavaScript綜合知識     

opener 與 parent 都是與視窗關係相關的屬性,但用途截然不同。本文詳細說明兩者的定義與使用時機,並附上實作範例。

opener:誰開啟了我

opener 指向開啟目前視窗的母視窗。例如 A 頁面以 window.open 彈出 B 視窗,那麼 A 就是 B 的 opener,在 B 中可透過 opener 存取 A 的內容。若引用失敗會回傳 null,因此使用前應先判斷是否為 null,否則會出現「對象為空或不存在」的錯誤。

parent:父視窗

parent 表示父視窗。例如 A 頁面以 iframe 或 frame 嵌入 B 頁面,那麼 A 就是 B 的 parent。

範例

a.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
</head>
<body>
<span id="name"></span>
<input type="button" value="彈窗" onclick="window.open('bb.html')" />
</body>
</html>

b.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
</head>
<body>
<input type="text" id="inputValue"/>
<input type="button" value="添加" onclick="window.opener.document.getElementById('name').innerHTML=inputValue.value"/>
</body>
</html>

在 b.html 中,即可透過 opener 將輸入值回寫到 a.html 的元素:

window.opener.document.getElementById("name").value = "輸入的數據";
window.opener.document.getElementById("name").innerHTML= "輸入的數據";

簡單來說,opener 用於 window.open 開啟的新視窗之間溝通,而 parent 則用於 iframe/frame 的巢狀結構,兩者不可混用。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved