JavaScript通过URL参数与window.opener实现页面间传值

作者:竹影

时间:2026-10-23

浏览:211

本文介绍一种通过URL参数和window.opener实现子页面与父页面数据交互的方法。父页面利用循环遍历input元素,通过闭包将索引值作为参数传入子页面URL。子页面解析URL获取索引,利用window.opener访问父页面DOM并赋值,完成数据回传。

文章目录

JavaScript通过URL参数与window.opener实现页面间传值

其核心原理较为直观。首先通过getAttribute方法检查type属性以定位目标按钮,随后在按钮的onclick事件中,将当前循环索引i作为参数附加到URL中,从而传递至子页面。


具体实现代码如下:

<h2>input1</h2>
<input type="text" /><input type="submit" />
<h2>input2</h2>
<input type="text" /><input type="submit" />
<script type="text/javascript"><!--
var aInput = document.getElementsByTagName("input");
for (i = 0 ; i < aInput.length ; i++ )
{ 
( 
function (i){
if (aInput[i].getAttribute("type") == "submit")
{ 
aInput[i].onclick = function (){
window.open('b.html?'+i,'newwindow','height=100,width=400')
} 
} 
} 
})(i)
} 
// --></script>

在子页面中,利用slice方法对URL字符串进行截取以获取传递的索引值。同时,通过window.opener属性获取父页面窗口对象,进而定位到父页面的文本框元素并赋值,即可完成整个交互流程。


子页面代码如下:

<h2>openWindow</h2>
<input type="text" /><input type="submit" />
<script type="text/javascript"><!--
var aInput = document.getElementsByTagName("input");
for (i = 0 ; i < aInput.length ; i++ )
{ 
if (aInput[i].getAttribute("type") == "text") var textboxB = new Object(aInput[i]);
if (aInput[i].getAttribute("type") == "submit") var btnB = new Object(aInput[i]);
} 
btnB.onclick = function(){
var sTextValue = textboxB.value
var aInput = window.opener.document.getElementsByTagName("input");
var sUrl = document.location;
var sNo = sUrl.toString().slice(-1)
window.opener.aInput[sNo-"1"].value = sTextValue
window.close();
} 
// --></script>

若对上述逻辑仍感困惑,可参考原理示意图以辅助理解。 e59bb31

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章