简单生活
返回文章列表
401 字3 分钟

window.parent与window.opener的区别与使用

设计开发#JavaScript

1、window.parent 是 iframe 页面调用父页面对象

举例: a.html

<html>
<head>
<title>A</title>
</head>
<body>
<form name="form1" id="form1">
<input type="text" name="username" id="username" />
</form>
<iframe src="b.html" width="100%"></iframe>
</body>
</html>

如果我们需要在 b.html 中要对 a.html 中的 username 文本框赋值(就如很多上传功能,上传功能页在 iframe 中,上传成功后把上传后的路径放入父页面的文本框中),我们应该在 b.html 中写:

<script type="text/javascript">
var _parentWin = window.parent;
_parentWin.form1.username.value = "xxxx";
</script>

Z-Blog 的文章编辑页面上传功能就是这么实现的。

2、window.opener 是 window.open 打开的子页面调用父页面对象

opener:对打开当前窗口的 window 对象的引用,如果当前窗口被用户打开,则它的值为 null。self 代表自身窗口,opener 代表打开自身的那个窗口,比如窗口 a.html 打开窗口 b.html。如果靠 window.open 方法,则对于窗口 b.html,self 代表 b.html 自己,而 opener 代表窗口 a.html。

举例:a.html

<input type="text" name="username" id="username" />
<a onclick="window.open(this.href,'','resizable=yes,width=800,height=600,status'); return false" href="b.html">B</a>

如果需要在 b.html 中对 a.html 中的表单元素赋值,我们应该在 b.html 中这么写:

<a
href="javascript:try{window.opener.document.getElementById('username').contentWindow.frames[0].document.getElementsByTagName('body')[0].innerHTML+='xxx'}catch(e){};window.close();"
>插入</a
>

在后面用 window.close 关闭 b.html。WindsPhoto 2.7.3 中在文章编辑页面弹出新窗口(图片列表)后,选择插入已上传图片便是如此实现的。