DIV CSS 佈局教程網

JS 彈窗返回值詳解(window.open 方式)
編輯:關於JavaScript     

用 window.open 打開子窗口後,往往需要把子窗口的數據回傳給父窗口。常見做法是利用 window.opener 取得父窗口引用,再操作父窗口的 DOM。下面以兩個頁面為例說明。

父頁面 test.php

代碼如下:

<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
function winOpen()
{
       window.open ("test2.php", "", "height=400, width=400");
}
</script>
</head>
<body>
<textarea id="text1" name="text1"></textarea>
<input type="button" value="submit" name="submit" onclick="javascript:winOpen();" />
</body>
</html>

子頁面 test2.php

代碼如下:

<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
function winBack()
{
    if(window.opener) {
                fWindowText1 = window.opener.document.getElementById("text1");
                fWindowText1.value = fWindowText1.value + "mayongzhan";
                window.close();
    }
}
</script>
</head>
<body>
<input type="button" name="back" value="back" onclick="javascript:winBack();" />
</body>
</html>

子頁面透過 window.opener 拿到父窗口對象,再找到 id 為 text1 的文本框,把內容追加進去後關閉自己。使用前務必先判斷 window.opener 是否存在,否則可能報「對象為空」的錯誤。

window.open 語法詳解

window.open("sUrl","sName","sFeatures","bReplace");

sUrl(可選):要加載的 HTML 文檔 URL,若省略則打開 about:blank。
sName(可選):窗口名稱,可用於 form 或 a 的 target,也可使用 _blank、_parent、_self、_top 等通用名稱。
sFeatures(可選):窗口裝飾樣式,多個之間以逗號隔開,僅在新窗口建立時生效。常用值包括:
channelmode、directories、fullscreen、height(最小 100)、width(最小 100)、left、top、location、menubar、resizable、scrollbars、status、titlebar、toolbar,取值均為 yes/no 或 1/0。
bReplace(可選):布爾值。false 表示新文檔覆蓋歷史列表中的當前任,true 表示追加到歷史列表末尾。

返回值:返回對新 window 對象的引用。說明:打開新窗口並載入指定文檔;當 sFeatures 被指定時,未列出的裝飾樣式會自動設為 no。另外,當 open 由事件中的函數呼叫時使用的是 window 對象的 open 方法,若直接在事件中使用 open 則調用的是 document 對象的 open 方法,二者含義不同,需注意區分。

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