jQuery 如何从父页面调用 iframe 中的函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4132411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:43:46  来源:igfitidea点击:

How to call a function in an iframe from the parent page?

jquery

提问by fgfgfgghjh

How to call a function in an iframe from the parent page?

如何从父页面调用 iframe 中的函数?

回答by Andy E

As long as the framed page is on the same domain (or on a sub-domain, and you're setting document.domain), you need to access the contentWindowproperty of the frame element. For example:

只要框架页面在同一个域中(或在子域中,并且您正在设置 document.domain),您就需要访问框架元素的contentWindow属性。例如:

$("#myFrame")[0].contentWindow.myFunction();

// or, if jQuery hasn't made you lazy 
document.getElementById("myFrame").contentWindow.myFunction();

Most browsers also support contentDocument, but Internet Explorer doesn't. If your framed page is on a different domain then you'll get an Access Denied error.

大多数浏览器还支持contentDocument,但 Internet Explorer 不支持。如果您的框架页面位于不同的域中,那么您将收到拒绝访问错误。

回答by GigolNet Guigolachvili

$("iframe").each(function()
{
    $(this).one("load", function()
    {
        $(this)[0].contentWindow.myFunction();
    });
});

It is necessary to loaded iframe ;)

有必要加载 iframe ;)

回答by MSS

Do it like a pro:

像专业人士一样做:

$("#myFrame").prop('contentWindow').abc();

回答by Maurizio Cucchiara

did you try?

你试过了吗?

top.frames['my_frame'].myFunc();

回答by Alex Rashkov

You can select the iFrame using its id

您可以使用其 id 选择 iFrame

document.getElementById(iframeId).contentDocument

but I am not sure you can access its JavaScript, especially if child iFrame is from different domain

但我不确定您是否可以访问它的 JavaScript,特别是如果子 iFrame 来自不同的域