跨iframe 执行js函数

来源:互联网 发布:雷神3彩蛋 知乎 编辑:程序博客网 时间:2024/05/16 16:59

Posted on 2010-07-30 19:19 千羽天明

主窗口中的代码:

1
2
3
4
5
6
<scripttype="text/javascript">
    window.gogo = function (){alert('这是来自主窗口的信息');}
</script>
<iframeid="test"name="test"src="testb.html"width="200"height="300"style="border:3px solid #333;"></iframe>
<inputtype="button"value="执行iframe中的函数" onclick="window.frames['test'].gogo()"/>

Iframe中的代码:

1
2
3
4
<scripttype="text/javascript">
    window.gogo = function(){alert('这是来自iframe的信息');}
</script>
<inputtype="button"value="执行主窗口中的函数"onclick="window.parent.gogo()"/>

window.frames['test'].gogo() 也可以写成 window.frames['test'].window.gogo(),但window.frames['test'] != window.frames['test'].window

alert( window.frames['test'] ) 返回的是 object DOMWindow, alert(window.frames['test'].window) 同样返回的是object DOMWindow,看来这里也能默认window。

同理:

window.frames['test'].window == document.getElementById('test').contentWindow

window.frames['test'] == document.getElementById('test').contentWindow

在ie6 ie7 ie8 firefox3.6 chrome中测试通过

 

原创粉丝点击