从 iframe 在父窗口中设置变量 [英] Set variable in parent window from iframe
问题描述
我有一个带有嵌入式 iframe 的父文档.在 iframe 内,我有一个上传字段.一旦用户选择了要上传的文件,我就会触发一个 jQuery 更改事件.在那个事件中,我想将父窗口中的变量设置为 true,以便父窗口知道上传已经开始.
I have a parent document with an embedded iframe. Inside the iframe I have an upload field. Once the user selects a file to upload, I trigger a jQuery change event. On that event I want to set a variable in the parent window to true, so that the parent knows that the upload has started.
有人知道怎么做吗?
正在尝试这个,但没有奏效:
Was trying this, but didn't work:
var test;
$("#newsletter_email").change(function() {
parent.window.test = true;
});
$('#send').click(function() {
if (test) {
alert('File has been uploaded!');
} else {
alert('You need to upload a file');
}
});
推荐答案
全局范围内的变量作为其包含的 window
对象的 DOM 属性自动公开.
Variables in the global scope are auto-exposed as DOM properties of their containing window
object.
这意味着
var foo = 'bar';
类似于
window.foo = 'bar';
这意味着您可以读取可以获取引用的任何 window
对象的全局范围.我们在这里还可以暗示的是,window
的用法是隐式.即使您没有明确输入window.",它仍然存在.
Which means that you can read the global scope of any window
object you can obtain a reference to. What we can also imply here is that usage of window
is implicit. Even when you don't explicitly type "window.", it's there anyway.
而且由于框架本身也自动公开为当前window
对象的DOM属性,这意味着您可以访问任何其他框架的window代码>对象也是如此.
And since frames themselves are also auto-exposed as DOM properties of the current window
object, this means you can access any other frames' window
object as well.
window
对象的 parent
属性保存了该窗口父级的 window
对象的引用(如果有的话).既然 iframe 肯定有一个父窗口,那么我刚刚输入的所有这些东西都归结为这个
The parent
property of window
objects holds a reference the window
object of that window's parent (if there is one). Since iframes most certainly have a parent window, then all this stuff I just typed boils down to this
// set the global variable 'foo' in the parent global scope
parent.foo = 'bar';
这篇关于从 iframe 在父窗口中设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!