javascript - 如何访问Iframe父窗口的方法[Chrome浏览器]

标签 javascript jquery html iframe

我尝试了很多次和很多方法来从 iframe 内部调用该方法,但尚未成功。请看下面,

  1. main.html : 由两个 iframe 组成

  2. iframe-1 与 index.html 链接,我想从其中调用 main.html 的方法或想要更改第二个 iframe 的 src。

ma​​in.html

<html> 
    <head> </head>
    <body>
     <iframe id="iframe-1" src="index.html"></iframe>
     <iframe id="iframe-2" ></iframe>
    </body>
</html>

index.html

<html> <head> 
<script type="text/javascript">
 $(document).ready(function(){
    // How to access the method of main.html and change the iframe src
 });
</script>
</head> <body>
    ......
</body> </html>

注意:尝试了parent.methodName()window.parent.methodName()不起作用

@EDIT:在 IE 和 MOZILLA 上成功,但在 Chrome 上出现错误(无法调用未定义的“getElementById”方法)

最佳答案

你应该尝试使用

document.getElementById("iframe-1").contentWindow.func();

var $f = $("#myIFrame");
var fd = $f[0].document || $f[0].contentWindow.document; // document of iframe
fd.MyFunction();  // run function

Docs

关于javascript - 如何访问Iframe父窗口的方法[Chrome浏览器],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17612514/

相关文章:

jquery - 计算剩余项目以计算百分比

jQuery Flexslider 不是每次都加载

html - @ViewChild 返回未定义的 Angular 8

html - 当我向下还原页面时,网页元素会移动

javascript - 如何从使用 "Input Type"= HTML 文件上传的文件中读取内容

javascript - Jquery onchange Ajax

jquery - asp.net/jQuery : post data with jQuery to a popup [IE]

javascript - 为什么表格不能拉伸(stretch)到 100% 宽度

javascript - 需要来自变量值的 AMD 风格的类?

jquery - $http 和 $ajax 请求在 Chrome 中随机返回状态 0