js iframe子页面调用主页面方法.html

本文介绍了一种在子页面中调用父页面方法的技术,通过使用window.parent,子页面能够与父页面进行交互,实现跨iframe的操作。具体演示了如何在子页面通过按钮点击调用父页面定义的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>

<html lang="zh-CN">

  <head>

    <meta charset="UTF-8" />

    <title>04.子页面调用主页面方法</title>

    <script>

      /* https://blog.csdn.net/qq_27626333/article/details/77990196

       * 在iframe本页面,要操作这个iframe的父页面的DOM元素(即嵌套这个iframe的页面)

       * 可以用:window.parent、window.top(这里的TOP是获取的顶层,即有多层嵌套iframe的时候使用)

       * */

      function parentValue() {

        /* 被 子页面 调用。*/

        if (confirm('欢迎访问:http://blog.csdn.net/qq_27626333')) {

          location.href = 'http://blog.csdn.net/qq_27626333'

        }

      }

    </script>

  </head>

  <body>

    <iframe id="myFrame" src="05.childWeb.html" width="510px" height="150px;"></iframe>

  </body>

</html>

<!DOCTYPE html>

<html lang="zh-CN">

  <head>

    <meta charset="UTF-8" />

    <title>05.childWeb</title>

    <style>

      .contain {

        display: flex;

        flex-direction: column;

        /*flex-direction: row;*/

        width: 500px;

      }

      #test {

        border: solid royalblue 2px;

        border-radius: 4px;

        width: 100%;

        color: #797979;

        height: 50px;

        line-height: 50px;

        font-size: 20px;

      }

      #button {

        border: solid #20a0ff 2px;

        border-radius: 4px;

        margin: 20px auto;

        padding: 10px;

        background-color: #20a0ff;

        color: white;

      }

    </style>

    <script>

      function parentValue() {

        /* 在子页面中,调用主页面(父页面)的方法。*/

        window.parent.parentValue()

      }

    </script>

  </head>

  <body>

    <div class="contain">

      <input

        type="text"

        id="test"

        value="欢迎访问:http://blog.csdn.net/qq_27626333"

      />

      <input

        type="button"

        id="button"

        value="调用主页面方法"

        onclick="parentValue()"

      />

    </div>

  </body>

</html>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值