首页 > 在父级中获取子级iframe框架中的方法,疑问

在父级中获取子级iframe框架中的方法,疑问

父级代码

<body>
<iframe name="my" src="a.html" border="0"></iframe>        
<script>
    frames[0].fn1();    
</script>
</body>

子级a.html的代码

<script>
        var i = 0;
        function fn1(){
            alert("这里是子窗口");
        };
    </script>

在父级中调用a.html的方法fn1,在firefox的代码草稿纸中运行ok,但是在源代码中运行报错
TypeError: frames[0].window.fn1 is not a function

frames[0].fn1();    

父框架不能调用子框架的函数吧?

能调用,真好!


最后还是用window的方法进行解决,需要层层地调试,一点不注意都会出错,我写了一个父级与两个兄弟之间相互调用方法的例子,直接使用window方法,更简洁!!!

a.html 如下

<body>
<iframe id="b" src="b.html" frameborder="0"></iframe>        
<iframe id="c" src="c.html" frameborder="0"></iframe>        
<script>
    var b =    frames[0]; 
    var c =    frames[1]; 
    setTimeout(function (){
        console.log(b.i);
    },3000);
</script>
</body>

b.html 如下

<body>
    <script>
        var i = "this is b";
        setTimeout(function (){console.log(parent.c.i)},2000);
    </script>        
</body>

c.html 如下

<body>
    <script>
        var i = "this is c"
        setTimeout(function (){console.log(parent.b.i)},1000);
    </script>        
</body>

如果不跨域,直接使用2楼方法;如果跨域,使用web worker传递数据,或者其他的跨与方法;


可以试试("iframeID")[0].contentWindow.方法名称();

【热门文章】
【热门文章】