iframe 的页面方法调用学习

 

外部调用iframe里的方法

document.getElementById('test21').contentWindow.saveData()
window.test21.saveData();
// test21是iframe的name值



iframe里的界面调用外部界面方法

window.parent.fnTest20()

 

效果图 


父html 

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<style>

</style>

<body>
  <div class="point point-flicker">
    test20
    <button οnclick="onSet()">点击</button>
  </div>
  <iframe id="test21" name='test21' src="./test21.html" frameborder="0"></iframe>
</body>
<script>
  // document.getElementById('test21').contentWindow.saveData()
  onload = function () {
    document.getElementById('test21').contentWindow.saveData()
  }

  function onSet() {
    document.getElementById('test21').contentWindow.saveData()

    // window.test21.saveData() // test21是iframe的name值
  }

  function fnTest20() {
    console.log('fnTest20')
  }
</script>

</html>

子html 

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<style>

</style>

<body>
  <div class="point point-flicker">
    test21
    <button οnclick="onSet()">点击</button>
  </div>
</body>
<script>
  function saveData() {
    console.log("test21")
  }
  
  function onSet() {
    window.parent.fnTest20()
  }
</script>

</html>

*****************遇到的坑********************

报错一 

可能是因为获取iframe的时候还没有加载完成,绑定一个onload事件试一下:

  onload = function () {
    document.getElementById('test21').contentWindow.saveData()
  }

报错二 

 

 使用Iframe时出现了这个错误,网上找了半天,都只是说将file://这个改为localhost....然并卵

后来想到,会不会是本地服务器问题,就通过vscode下了一个live server, 然后右击,运行,搞定

如果不是用来测试的话,应该使用Nginx服务器进行解决

发布了171 篇原创文章 · 获赞 499 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qq_43258252/article/details/103033663