欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

关于Iframe父页面与子页面之间的相互调用

时间:2021-04-26 11:02:34|栏目:JavaScript代码|点击:

iframe元素就是文档中的文档。

window对象: 浏览器会在其打开一个HTML文档时创建一个对应的window对象。但是,如果一个文档定义了一个或者多个框架(即:包含一个或者多个frame或者iframe标签),浏览器就会为原始文档创建一个window对象,再为每个iframe创建额外的window对象,这些额外的window对象是原始窗口的子窗口。

contentWindow: 是指指定的iframe或者iframe所在的window对象

Demo1

父页面fu.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>父页面</title>
  </head>
  <body>
  <input type=button value="调用子页面中的函数childSay函数" onclick="callChild()">
  <iframe id="myFrame" src="zi.html"></iframe>
  <script type="text/javascript">
function parentSay() {
alert("我是父页面中的方法");
}
function callChild()
{
document.getElementById("myFrame").contentWindow.childSay();
}
  </script>
  </body>
</html>

子页面zi.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>子页面</title>
  </head>
  <body>
  <input type=button value="调用父页面中的parentSay()函数" onclick="callParent()">
  <script type="text/javascript">
function childSay()
{
alert("我是子页面的say方法");
}
function callParent() {
parent.parentSay();
}
  </script>
  </body>
</html>

Demo2

父页面iframe1.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>父页面与子页面之间的调用</title>
  </head>
  <body>
  <iframe src="http://localhost/iframe/iframe3.html" id="iframe3"></iframe>
  <iframe src="http://localhost/iframe/iframe2.html" id="iframe2"></iframe>
  <div class="iframe1">我是父页面</div>
  <script type="text/javascript">
  var iframe2=document.getElementById('iframe2');
  iframe2.onload=function(){//父页面调用子页面中的方法
    iframe2.contentWindow.b();
  };
  function test2() {
    console.log("我是父页面中的方法,在子页面中调用的");
    return iframe2;
  }
  </script>
  </body>
</html>

子页面iframe2.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>子页面</title>
  </head>
  <body>
  <div id="test">aaa</div>
  <div class="iframe2">子页面</div>
  <script type="text/javascript">
  //子页面iframe2.html调用父页面iframe1.html的函数:
   parent.test2();
   function b(){
      console.log("我是子页面iframe2");
    }
    function c() {
      console.log("iframe3页面调用iframe2页面");
    }
  </script>
  </body>
</html>

子页面iframe3.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>iframe3</title>
  </head>
  <body>
  <script type="text/javascript">
  var iframe2=parent.test2();
  iframe2.contentWindow.c();//iframe3调用iframe2中的方法
  </script>
  </body>
</html>

Demo2也实现了子页面与子页面之间相互调用。

上一篇:js过滤特殊字符输入适合输入、粘贴、拖拽多种情况

栏    目:JavaScript代码

下一篇:javascript递归回溯法解八皇后问题

本文标题:关于Iframe父页面与子页面之间的相互调用

本文地址:http://www.codeinn.net/misctech/108819.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有