当前位置: 代码迷 >> 综合 >> js中 opener和parent的介绍及区别
  详细解决方案

js中 opener和parent的介绍及区别

热度:28   发布时间:2024-01-19 10:30:28.0

opener即谁打开我的,比如A页面利用window.open弹出了B页面窗口,那么A页面所在窗口就是B页面的

opener,在B页面通过opener对象可以访问A页面。

parent表示父窗口,比如一个A页面利用iframe或frame调用B页面,那么A页面所在窗口就是B页面的

parent。

在JS中,window.opener只是对弹出窗口的母窗口的一个引用。比如:
a.html中,通过点击按钮等方式window.open出一个新的窗口b.html。那么在b.html中,就可以通过

window.opener(省略写为opener)来引用a.html,包括a.html的document等对象,操作a.html的内容。
假如这个引用失败,那么将返回null。所以在调用opener的对象前,要先判断对象是否为null,否则会

出现“对象为空或者不存在”的JS错误。

<html>
<body>
<form. name=form1>
<input type=text name=inpu >
<input type=button   >
</form>
</body>
</html>


--------------------------------
back2opener.html
--------------------------------
<html>
<body>
<form. name=form1>
<input type=text name=inpu >

   <a class=under href=# >添加</a>
</form>
</body>
</html>



window.opener 返回的是创建当前窗口的那个窗口的引用,比如点击了a.htm上的一个链接而打开了

b.htm,然后我们打算在b.htm上输入一个值然后赋予a.htm上的一个id为“name”的textbox中,就可以

写为:

window.opener.document.getElementById("name").value = "输入的数据";

 

对于parent的用法:

a.html网页包含如下内容
<iframe src="b.html">
<form name='form1'><input name="a" type="hidden" value=""></form>


现在我在 b.html 写入js 想让a.html 中的表单form1中的a值设置为0.1

parent.document.form1.a.value='0.1';
a.htm:

  1. <iframe src="b.html"></iframe>
  2. <form name='form1'>input name="a" type="text" value=""></form>

b.html:

  1. <input type="button" value="添加" onclick="window.parent.document.all.form1.a.value='我是新添加的内容';">
this.parent.style.width = this.width * 10 + 'px';

把本对象的父对象的宽度设置为本对象的10倍
  相关解决方案