JavaScript 父页面与子页面传值的两种实现方式

作者:像素漫游

时间:2026-10-27

浏览:554

本文介绍 JavaScript 中父页面与子页面相互传值的两种常见场景:通过 window.open 弹出的窗口和使用 iframe 框架嵌入的页面。分别讲解了利用 window.opener 和 parent 对象访问父页面 DOM 元素并修改其值的具体代码实现与操作步骤。

文章目录

通过 window.open 弹出的子页面传值

一、子页面由父页面通过window.open弹出的场景 子页面向父页面传递数值时,需在document前添加window.opener。 示例: 1.父页面代码:

<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.子页面代码:

通过 iframe 框架嵌入的子页面传值

<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框架内的场景 子页面向父页面传递数值时,需在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.子页面代码

<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>

实用工具推荐

电子包浆

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

使用 ›
图片压缩

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

使用 ›
相关文章