从 iFrame/Window 访问 JavaScript 中的父对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9774277/
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
Access parent object in JavaScript from iFrame/Window
提问by user823527
How do I access a global object or array defined in a parent window in the child window.
如何访问子窗口中父窗口中定义的全局对象或数组。
<script>
var events_data;
function function_to_fill_events_data () {
.
.
.
}
</script>
<div>
<div><iframe src="mini.php" width:100%; height: 100%;" scrolling="no"></iframe> </div>
</div>
When I am in the mini document I'd like to be able to access the events_data variable in a javascript function.
当我在迷你文档中时,我希望能够访问 javascript 函数中的 events_data 变量。
回答by James Hill
Option 1
选项1
Your title mentions a child window. If you have a child window, and not an iframe, use this:
你的标题提到了一个子窗口。如果您有一个子窗口,而不是 iframe,请使用以下命令:
window.opener.events_data
Check out window.opener
on MDN.
Option 2
选项 2
Your code indicates that you're using an iframe. From an iframe, simply use parent
:
您的代码表明您正在使用 iframe。从 iframe 中,只需使用parent
:
parent.events_data;
Check out window.parent
on MDN.
window.opener
- Returns a reference to the window that opened this current window.
window.opener
- 返回对打开当前窗口的窗口的引用。
window.parent
- When a window is loaded in an , , or , its parent is the window with the element embedding the window.
window.parent
- 当一个窗口在 、 或 中加载时,其父窗口是元素嵌入窗口的窗口。