从父页面调用 iframe 中的 JavaScript 代码 [英] Invoking JavaScript code in an iframe from the parent page
问题描述
基本上,我在页面中嵌入了一个 iframe
,iframe
有一些 JavaScript 我需要从父页面调用的例程.
Basically, I have an iframe
embedded in a page and the iframe
has some JavaScript routines I need to invoke from the parent page.
现在相反很简单,因为你只需要调用parent.functionName()
,但不幸的是,我需要完全相反的.
Now the opposite is quite simple as you only need to call parent.functionName()
, but unfortunately, I need exactly the opposite of that.
请注意,我的问题不是更改 iframe<的源 URL/code>,但调用在
iframe
中定义的函数.
Please note that my problem is not changing the source URL of the iframe
, but invoking a function defined in the iframe
.
推荐答案
假设你的 iFrame 的 id 是targetFrame",你要调用的函数是 targetFunction()
:
Assume your iFrame's id is "targetFrame" and the function you want to call is targetFunction()
:
document.getElementById('targetFrame').contentWindow.targetFunction();
您还可以使用 window.frames
而不是 document.getElementById
访问框架.
You can also access the frame using window.frames
instead of document.getElementById
.
// this option does not work in most of latest versions of chrome and Firefox
window.frames[0].frameElement.contentWindow.targetFunction();
这篇关于从父页面调用 iframe 中的 JavaScript 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!