Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/89.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从父窗口调用Iframe中的函数?_Javascript_Jquery_Html_Iframe - Fatal编程技术网

Javascript 从父窗口调用Iframe中的函数?

Javascript 从父窗口调用Iframe中的函数?,javascript,jquery,html,iframe,Javascript,Jquery,Html,Iframe,我想从父窗口调用Iframe中的函数。作为 var iframe = document.getElementById("myframe"); if (iframe) { var iframeContent = (iframe.contentWindow || iframe.contentDocument); iframeContent.targetFunction(); } 但它不起作用 由于Iframe的内容是动态添加的,所以所有内容都会按需添加到Iframe甚至js文件中 我

我想从父窗口调用Iframe中的函数。作为

var iframe = document.getElementById("myframe");
if (iframe) {
   var iframeContent = (iframe.contentWindow || iframe.contentDocument);

   iframeContent.targetFunction();
}
但它不起作用

由于Iframe的内容是动态添加的,所以所有内容都会按需添加到Iframe甚至js文件中

我遵循了这一点

有什么办法可以解决这个问题吗?

html中有一个叫做postmessage的概念

在相应的脚本中尝试下面的代码

父母

在iFrame中

参考:


希望有帮助

一把小提琴就好了@在尝试我的答案之前,Brunt无法创建fiddle。尝试使用parent.functionName直接调用函数。如果不起作用,请使用我的answer@Brunis这个问题是而且应该毫不迟疑地回答。它们在问题中不是必需的,这是真的,但是有一些示例代码可以使用是很好的,这也表明他做出了努力。这不是一个为我做这个任务的网站。
if (window.addEventListener) {
    window.addEventListener ("message", receive, false);        
}
else {
    if (window.attachEvent) {
        window.attachEvent("onmessage",receive, false);
    }
}

function receive(event){
    var data = event.data;
    if(typeof(window[data.func]) == "function"){
        window[data.func].call(null, data.params[0]);
    }
}

function alertMyMessage(msg){

    alert(msg);
}
function send(){
    window.parent.window.postMessage(
        {'func':'alertMyMessage','params':['Thanks for Helping me']},
        'http://www.my-website.com'
    );
}