iframe父子页面传值_iframe父子页面相互调用js代码

更新时间:2018-02-19    来源:js教程    手机版     字体:

【www.bbyears.com--js教程】

当父页面和子页面都属于同一个域下,那么它们之间的js方法是可以相互调用的。在调用方法前指定function所属对象即可,父页面获取iframe所属对象方法为:iframe的name.window.方法名(),iframe页面获取父页面所属对象方法为:parent.方法名()。
但是这里有一个非常重要的限制,由于浏览器基于安全考虑,是不允许js在不同域名间进行通信,所以父子页面必须属于同一个域,即使是相同主域下的不同二级域也是不行的。
对于父子页面完全属于两个不同的域名,那么它们之间永远无法直接进行通信;如果父子页面是属于同一个主域下的不同二级域,则可以使用强制设置document.domain的方式来达到让其互相通信。document.domain默认值是window.location.host,可以js中设置为window.location.host的上一级域,但是不能为根域,例如:可以在页面www.duankou.com设置document.domain为duankou.com,但是不能设置为other.duankou.com或com。
document.domain在一定程度上解决了不同二级域名页面的跨域问题。需要注意的是,如果父页面包含多个iframe且设置了document.domain,那么要与其进行通信的iframe也必须设置document.domain。

iframe 父窗口和子窗口相互的调用方法

1、IE中使用方法:

父窗口调用子窗口:iframe_ID.iframe_document_object.object_attribute = attribute_value
例子:onClick="iframe_text.myH1.innerText="http://www.pint.com";"
子窗口调用父窗口:parent.parent_document_object.object_attribute = attribute_value
例子:onclick="parent.myH1.innerText="http://www.pint.com";"

2、Firefox中使用方法:

上面在IE下没有问题,但在firefox下不正常。在firefox下,应该是如下调用方法:

父窗口调用子窗口:window.frames["iframe_ID"].document.getElementById("iframe_document_object"­).object_attribute = attribute_value
例: window.frames["iframe_text"].document.getElementById("myH1").innerHTML= "http://hi.www.111cn.net";
子窗口调用父窗口:parent.document.getElementById("parent_document_object").object_attribute = attribute_value
例: parent.document.getElementById("myH1").innerHTML = "http://www.111cn.net";


具体例子如下:

父页面:parent.html

 代码如下





parent
<script>
 function parentFunction() {
  alert("function in parent");
 }

 function callChild() {
  child.window.childFunction();
  /*
   child 为iframe的name属性值,
   不能为id,因为在FireFox下id不能获取iframe对象
  */
 }
</script>








子页面:child.html

 代码如下





child
<script>
 function childFunction() {
  alert("function in child");
 }

 function callParent() {
  parent.parentFunction();
 }
</script>




本文来源:http://www.bbyears.com/wangyezhizuo/39363.html

热门标签

更多>>

本类排行