iframe中父页面与子页面的传值方法

涉及到iframe传值的情况有这么几种:(1)父页面给iframe中的子页面传值(2)子页面调用父页面中的函数(3)iframe中的子页面给父页面传值(4)兄弟iframe之间的传值

下面来逐一看一下:

(1)父页面给iframe中的子页面传值 ,把值写入子页面的文本框中

father.html

1 <script language="javascript" src="http://www.aspbc.com/js/jquery.js" type="text/javascript"></script>  
2 <script type="text/javascript">  
3 function fuzhi()  
4 {  
5     $('#son').contents().find("#b").val("父页面传过来的值!");   
6 }  
7 </script>  
8 <iframe id="son" name="son" src="son.html" width="400" height="200"></iframe><br /> 
9 <input type="button" value="给子页面表单中id为b的文本框赋值" onclick="fuzhi()" />
father.html

son.html

1 <form name="form2"><input type="text" name="b" id="b" /></form>
son.html

(2)子页面调用父页面中的函数 

father.html

1 <script language="javascript" src="http://www.aspbc.com/js/jquery.js" type="text/javascript"></script>  
2 <script type="text/javascript">  
3 function fun()  
4 {  
5     alert('这是父页面中的函数弹出窗口哦!');  
6 }  
7 </script>   
8 <iframe id="son" name="son" src="son.html" width="400" height="200"></iframe>
father.html

son.html

1 <script type="text/javascript">  
2 function diaoyong()  
3 {      
4     $(window.parent.fun());  //调用父页面函数  
5 }  
6 </script>  
7 <form name="form2"> <input name="btn1" type="button" onclick="diaoyong()" value="调用父页面中的函数" /></form>
son.html

(3)iframe中的子页面给父页面传值

father.html

1 <script language="javascript" src="http://www.aspbc.com/js/jquery.js" type="text/javascript"></script>  
2 <div id="messagediv">test</div>  
3 <iframe id="son" name="son" src="son.html" width="400" height="200">
4 </iframe>
father.html

son.html

1 <script type="text/javascript">  
2 function fuzhi()  
3 {  
4     $(window.parent.$("#messagediv").html("子页面赋过来的值"));  
5 }  
6 </script>  
7 <form name="form2"><input name="btn1" type="button" onclick="fuzhi()" value="给父页中id为messagediv的元素赋值" /></form>
son.html
原文地址:https://www.cnblogs.com/lihuibin/p/9558349.html