彈出式對話視窗常需要在父視窗與子視窗之間傳遞資料。本文以 window.showModalDialog 為例,完整說明父子視窗雙向傳值的做法。
var returnValue = window.showModalDialog(url [, arguments] [,features]);
url 是要顯示的文件的網址;arguments 是傳入對話框的參數,型別不限,包含陣列、物件皆可,對話框用 window.dialogArguments 接收;features 則用來描述對話框外觀,例如 dialogHeight、dialogWidth、center、resizable、status、scroll 等,以分號隔開。
parent.htm:
<script>
var obj = new Object();
obj.name="justflyhigh.com";
window.showModalDialog("modal.htm",obj,"dialogWidth=200px;dialogHeight=100px");
</script>
modal.htm 用 dialogArguments 接收:
<script>
var obj = window.dialogArguments;
alert("您傳遞的參數為:" + obj.name)
</script>
parent.htm:
<script>
var result =window.showModalDialog("modal.htm",,"dialogWidth=200px;dialogHeight=100px");
alert(result);
</script>
modal.htm:
<script>
window.returnValue="https://www.jb51.net";
</script>
透過 arguments 與 returnValue,父子視窗之間就能輕鬆完成雙向資料傳遞。