html中iframe调用兄弟iframe中的js方法

问题说明


最近工作中碰到一个页面有一个主iframe A,用于操作主要业务元素。其中有一个弹出框里面也嵌入了一个iframe B,

此时,我需要在B中调用A中JS的指定方法。下面咱们来通过例子还原一下这个场景,看如何实现的。


主页面html

testframe.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <iframe id="frame1" src="frame1.html" width="400px" height="300px"></iframe>
    <iframe id="frame2" src="frame2.html" width="400px" height="300px"></iframe>
</body>
</html>


iframe1即A页面


frame1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>iframe1</title>

    <script type="text/javascript">
        function frame1_func() {
            alert("你调用了frame1的函数!");
        }
    </script>
</head>

<body>
<h1>这是iframe1</h1>
</body>
</html>


iframe2即B页面


frame2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>iframe2</title>
    <script type="text/javascript" src="../js/jquery-1.4.4.min.js"></script>
    <script type="text/javascript">

        function frame2_func(){
            //调用frame1_func
            $(window.parent.document).contents().find("#frame1")[0].contentWindow.frame1_func();
        }
    </script>
</head>

<body>
    <h1>这是iframe2</h1><br>
    <button id="clickMe" οnclick="frame2_func()">点击我调用frame1方法</button>
</body>
</html>

测试结果







posted @   一锤子技术员  阅读(8)  评论(0编辑  收藏  举报  
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示