iframe子页面调用父页面javascript函数的方法
今天遇到一个iframe子页面调用父页面js函数的需求,解决起来很简单,但是在chrome浏览器遇到一点小问题。顺便写一下iframe的父页面调用子页面javascript函数的方法吧,备用!

1、iframe子页面调用 父页面js函数

子页面调用父页面函数只需要写上window.praent就可以了。比如调用a()函数,就写成:

window.praent.a();

但是我在chrome浏览器下却发现此方法无效了!查了半天才了解,在chrome 5+中,window.parent无法在file://协议中运行,但是发布了之后http://协议下是可以运行的。此方法支持ie、firefox浏览器。

2、iframe父页面调用 子页面js函数

这个就稍微复杂一些,下面的方法支持ie和firefox浏览器:

document.getElementById('ifrtest').contentWindow.b();

注:ifrtest是iframe框架的id,b()为子页面js函数。contentWindow属性是指定的frame或者iframe所在的window对象,IE下可以省略。

父页面(parent.html):

  1. <!DOCTYPE html >
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>parent</title>
  6. </head>
  7. <body>
  8. <input type="button" value="call child" onclick="callChild()"/>
  9. <iframe name="child" src="child.html" ></iframe>
  10. <script>
  11. function parentFunction() {
  12. alert('function in parent');
  13. }
  14. function callChild() {
  15. //child 为iframe的name属性值,不能为id,因为在FireFox下id不能获取iframe对象
  16. child.window.childFunction();
  17. }
  18. </script>
  19. </body>
  20. </html>

子页面(iframe页面,child.html):

  1. <!DOCTYPE html >
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>child</title>
  6. </head>
  7. <body>
  8. <input type="button" value="call parent" onclick="callParent()"/>
  9. <script>
  10. function childFunction() {
  11. alert('function in child');
  12. }
  13. function callParent() {
  14. parent.parentFunction();
  15. }
  16. </script>
  17. </body>
  18. </html>
04-26 16:34
查看更多