JS父页面与子页面相互传值方法
opener即谁打开我的,比如A页面利用window.open弹出了B页面窗口,那么A页面所在窗口就是B页面的opener,在B页面通过opener对象可以访问A页面。
一、子页面是父页面通过window.open弹出的情况 子页面要向父页面传值,只要在document前面加window.opener即可。
如:
1.父页面代码:
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的内容。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"
/>
<title>无标题文档title>
head>
<script language="javascript">
function tanchu()
{
window.open("Untitled-5.html");
}
script>
<body>
<form id="form1" name="form1" method="post" action="">
<label> <input type="submit" name="button" id="button"
value="提交"
onclick="tanchu()" />
label> <label> <input type="text" name="textfield"
id="textfield" />
label>
form>
</body>
</html>
2.子页面代码:
假如这个引用失败,那么将返回null。所以在调用opener的对象前,要先判断对象是否为null,否则会出现“对象为空或者不存在”的JS错误。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"
/>
<title>无标题文档title>
head>
<script language="javascript">
function aaa()
{
window.opener.document.getElementByIdx('textfield').value='123123123';
}
script>
<body>
<form id="form1" name="form1" method="post" action="">
<label> <input type="submit" name="button" id="button"
value="提交"
onclick="aaa()" />
label>
form>
</body>
</html>
二、子页面是iframe框架中的页面情况
示例:
aa.html
子页面要向父页面传值,只要在document前面加parent即可。
1.父页面代码:
复制代码 代码如下:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"
/>
<title>无标题文档title>
head>
<body>
<form id="form1" name="form1" method="post" action="">
<label> <input type="text" name="textfield"
id="textfield" />
label>
<iframe id="myiframe" src="Untitled-3.html">iframe>
form>
</body>
</html>
2.子页面代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"
/>
<title>无标题文档</title>
</head>
<body>
<span id="name"></span>
<input type="button" " value="弹窗" onclick="window.open('bb.html')"
/>
</body>
</html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"
/>
<title>无标题文档title>
head>
<script language="javascript">
function aa()
{
var a=parent.document.getElementByIdx('textfield').value;
alert(a);
}
script>
<body>
<form id="form1" name="form1" method="post" action="">
<label> <input type="submit" name="button" id="button"
value="提交"
onClick="aa()" />
label>
form>
</body>
</html>