window.open()用于打开一个新的浏览器窗口或查找一个已命名的窗口。
window.open(URL,name,features,replace)
1. window.open()由父页面向子页面传递参数
可以看到,open()方法中并不包含可以传递给子页面的参数,所以要想把参数传递给子页面,我们需要将传递的参数写到子页面的URL中,但是这种方法只能用于传递一些比较小的参数,比如标签的id之类的。下面我把a.html中的参数通过url传递给b.html,并让他显示在对话框中。
a.html
<body>
<h3>传递到子页面</h3>
<input type="text" value="233" id="txtStartTime" />
<input type="button" value="打开新页面" id="btn1" οnclick="sendtob()" />
<h3>传递回来的参数</h3>
<input type="text" id="txtEndTime" />
</body>
javascript
<script>
function sendtob(){
var sourcename = document.getElementById("txtStartTime").value;
window.open("b.html?id="+sourcename,"我是子页面","width=300,height=400,top=200,left=300,toobar=no,menubar=no,scrollbars=no,location=no,status=no");
}
</script>
可以看到我在open()方法的URL中增加了"?id=233"这样的字段,这样的话当你打开b.html时时可以在地址栏看到这个参数的,也就是说,当你用这个方法进行参数传递时是无法对信息进行加密的。之后在子页面中可以中window.location.search来获取url中问号及之后的值。
即:window.location.search="?id=233"
如此以来,我们便完成了从父页面到子页面的参数传递
b.html
<body>
<h3>来自父页面a.html的参数</h3>
<input type="text" id="a1"/>
<h3>传递到父页面</h3>
<h3>因为协议不同涉及域的问题,请部署到localhost再向父页面传参</h3>
<input type="text" id="a2" value=""/>
<input type="button" value="传参并关闭页面" onclick = "sendtoa()"/>
<script>document.getElementById("a1").value = afterEqual;</script>
</body>
javascript
<script>
//(问号以后的字符串)即id=233
var afterUrl = window.location.search.substring(1);
//(等号以后的字符串,及你所要的参数)即233
var afterEqual = location.search.substring(1).split('=')[1];
function sendtoa(){
window.opener.document.getElementById("txtEndTime").value=document.getElementById("a2").value;
console.log(document.getElementById("a2").value);
}
</script>
在b.html中,可以通过window.opener方法来直接操作父页面内的标签或者调用方法,
总结:可以将标签id通过URL传递给子页面,然后由子页
面用window.opener方法通过id直接操作标签,或者调
用方法。
a.html b.html下载连接 百度网盘: 点击打开链接