DIV CSS 佈局教程網

彈出視窗並回傳數值:showModalDialog 與 window.open 兩種做法
編輯:關於JavaScript     

方法一:window.showModalDialog

語法:

window.showModalDialog(url, args, dialogattrs)
  • url:彈出頁面的位址。
  • args:主視窗傳給對話框的參數,型別不限,陣列也可以。
  • dialogattrs:視窗樣式設定,例如 resizable:yes、dialogWidth、dialogHeight 等。

主視窗側:

var value = window.showModalDialog('test.jsp', strs, 'resizable:yes');

彈出視窗內透過 window.returnValue 設定回傳值,主視窗的 value 拿到的就是它,接著就能做後續處理。

重點:模式對話框的價值就在這個回傳值——可以是簡單字串,也可以是陣列。

方法二:window.open

父視窗:

<script>
function show_child() {
    var child = window.open("child.html", "child",
        "height=200,width=400,status=yes,toolbar=no,menubar=no,location=no");
}
</script>
<a href="javascript:show_child();">打開子窗口</a>
<form name=frm0>
  <input type="text" name="txt0" id="txt0"> <!-- 一定要寫 id,否則 FF 下取不到值 -->
</form>

子視窗:

<script>
function choseItem() {
    var v = "";
    var check_item = document.frm.item;
    for (i = 0; i < check_item.length; i++) {
        if (check_item[i].checked) { v += "," + check_item[i].value; }
        document.frm.txt.value = v.replace(/^,{1}/, "");
    }
}

function foo() {
    window.close();
    window.opener.document.getElementById("txt0").value =
        document.getElementById("txt").value;
}
</script>

<form name=frm>
  <input type=checkbox name=item value=1 onclick="choseItem();">a
  <input type=checkbox name=item value=2 onclick="choseItem();">b
  <input type=checkbox name=item value=3 onclick="choseItem();">c
  <input type=checkbox name=item value=4 onclick="choseItem();">d
  <input type=text name="txt" id="txt">
</form>
<input type=button value="關閉" onclick="foo();">

關鍵是透過 window.opener 取得開啟它的父視窗,再直接寫入父視窗的欄位。

該選哪一個?

window.open 可以自訂的項目多、彈性大,因此實務上用得較廣;不少網頁編輯器偏愛 showModalDialog,因為它天生有回傳值、也更好控制焦點。若實在拿不主意,window.open 是保險選擇——許多成熟的 CMS 系統都是走這條路。

要留意的是 showModalDialog 屬於舊式 IE 的專有功能,標準瀏覽器並未實作,跨瀏覽器專案應該以 window.open 搭配 opener 為主,或改用 postMessage 溝通。

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