由于在项目中遇到了这个问题,在这里记录下来。
现在我们需要在子窗口的文本框中输入一个值,由父窗口去记录,每次打开子窗口的时候判断父窗口是否有记录值,如果有 就直接将父窗口中记录的值现在在子窗口的文本框中。
(不是用的iframe 如果用iframe调用父类用window.parent 可为什么?我也不明白)
我们先用普通打开方式:
一、子窗口输入值显示在父窗口中
需要用到的函数写到 子窗口中
window.opener.myForm.userName.value
获取到父类文本框 可以赋值,可以取值
二、代码
父页面:aa.html
<html>
<head>
<title>父页面</title>
<script type="text/javascript">
function openSubWin()
{
OpenWindow = window.open('bb.html', 'newwindow', 'height=1024, width=1300, top=0, left=0, toolbar=no, menubar=yes, scrollbars=yes,resizable=yes,location=no, status=no');
}
</script>
</head>
<body>
<form name="form1" id="form1">
<input type="text" name="userName" id="userName"/>
<input type="button" value="弹出子页面" onclick = "openSubWin()">
</form>
</body>
</html>
子页面:bb.html
<html>
<head>
<title>子页面</title>
<script type="text/javascript">
function UpdateParent()
{
window.opener.form1.userName.value = document.getElementById("bb1").value ;
}
//调用父类记录的值
function childInvokeParent()
{
document.getElementById("bb1").value=window.opener.form1.userName.value;
}
</script>
</head>
<body>
<form name="form1" id="form1">
<p> </p>
<p align="center">
<input id="bb1" name="bb1">
<input type="button"
onclick = "UpdateParent();"
name="button"
id="button"
value="更新父页面的UserName内容">
<input type = "button"
name = "button2"
id = "button2"
value = "测试子窗口调用父窗口记录的值"
onclick = "childInvokeParent();"/>
</p>
<p> </p>
</form>
</body>
在传的时候还遇到一个问题就是用模式窗口打开的子窗口。。如果用上面的方法显示会报异常找不到对象的。
模式窗口的方法:
父页面:a1.html
<html>
<head>
<title>父页面</title>
<script type="text/javascript">
//传到子类的一定要是个window对象
function openSubWin()
{
window.showModalDialog("b1.html",window,"dialogHeight:100px,center:yes,resizable:no,status:no");
}
</script>
</head>
<body>
<form name="form1" id="form1">
<input type="text" name="username" id="username"/>
<input type="button" value="弹出子页面" onclick = "openSubWin()">
</form>
</body>
</html>
子页面:b1.html
<html>
<head>
<title>子页面</title>
<script type="text/javascript">
function UpdateParent()
{
var bb1 = document.getElementById("bb1").value;
window.dialogArguments.form1.username.value = bb1 ;
}
function childInvokeParent()
{
document.getElementById("bb1").value=window.dialogArguments.form1.username.value;
}
</script>
</head>
<body>
<form name="form1" id="form1">
<p> </p>
<p align="center">
<input id="bb1" name="bb1">
<input type="button"
onclick = "UpdateParent();"
name="button"
id="button"
value="更新父页面的UserName内容">
<input type = "button"
name = "button2"
id = "button2"
value = "测试子窗口调用父窗口记录的值"
onclick = "childInvokeParent();"/>
</p>
<p> </p>
</form>
</body>
用模式窗口打开的时候一定要传一个window对象过去
网上一篇关于window.showModalDialog()返回值,可以看看
http://blog.csdn.net/liang4571231/archive/2009/04/24/4105712.aspx