1 、不能使用 window.parent
Window.parent 是用來在 frame 中進行操作的,在對話框中不能用來操作父窗口對象
?
2 、正確的做法
?
調用 modaldialog 時通過傳參數的方式操作
例:
需求
父窗口頁面為 a.html 子窗口頁面為 b.html 。 a.html 中有文本框 id 為 test1 ,在打開的對話框中點擊按鈕,將 a.html 的文本框值改為“子窗口值”。
實現
打開對話框時把 test1 作為參數傳給子窗口,在子窗口中獲取參數,將參數對象(即 a.html 中傳過來的 text 對象)的 value 屬性值設置為“子窗口值”
注意:這里只能傳 id ,不能傳 name
?
a.html 代碼如下
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>a.html</title>
</head>
<body>
<input type=text id=test1 value=''>
<input type=button value=" OK " onclick='window.showModalDialog("b.html", test1)'>
</body>
</html>
?
b.html 代碼如下
?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>b.html</title>
<script language=javascript>
function func1(){
//獲取父窗口傳過來的參數
var ptextid = window.dialogArguments;
if(ptextid != undefined){
//將父窗口傳過來的對象的值改為“子窗口值”
ptextid.value = "子窗口值";
//關閉子窗口
window.close();
}
}
</script>
</head>
<body>
<input type=button value=" OK " onclick=func1()>
</body>
</html>
?
?
如果需要操作的父窗口對象比較多,也可以將 window 或window.document作為參數傳給子窗口。
例:
需求
a.html 中添加 id 為“ aform ”的的 form , form 中有 id 為 test2 的文本框,在 b.html 中,除了進行上面的操作之外,還要將 test2 的值改為“子窗口值 2 ”,并將 form 提交到 c.html 。
實現 1
將 a.html 中打開對話框的函數改為如下方式 :
window.showModalDialog("b.html", window.document) ;
?
將 b.html 中 func1() 改為如下 :
?
function func1(){
var pdoc = window.dialogArguments;
if(pdoc!=undefined){
pdoc.all.test1.value="子窗口值";
pdoc.all.test2.value="子窗口值2";
pdoc.all.aform.action="c.html";
pdoc.all.aform.submit();
}
}
?
?
實現 2
因為在子窗口中對父窗口進行的操作比較多,也可以采用execScript的方式實現。
?
將 a.html 中打開對話框的函數改為如下方式 :
window.showModalDialog("b.html", window) ;
?
添加 javascript 函數如下
function func(){
test1.value="子窗口值";
document.all.test2.value="子窗口值2";
aform.action="c.html";
aform.submit();
}
?
將 b.html 中 func1() 改為如下 :
?
function func1(){
var pwin = window.dialogArguments;
if(pwin!=undefined){
var codeStr = "func();"
pwin.execScript(codeStr,"javascript");
window.close();
}
}