在iframe的父窗口中设置变量 [英] Set variable in parent window from iframe

查看:124
本文介绍了在iframe的父窗口中设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有嵌入式iframe的父文档。在iframe里面我有一个上传字段。一旦用户选择要上传的文件,我将触发一个jQuery更改事件。在该事件中,我想在父窗口中设置一个变量为true,以便父母知道上传已经开始。



有没有人知道如何做?



正在尝试这个,但没有起作用:

  var测试; 
$(#newsletter_email)。change(function(){
parent.window.test = true;

});

$('#send')。click(function(){
if(test){
alert('File has been uploaded!');
} else {
alert('你需要上传一个文件');
}
});


解决方案

全局范围中的变量将自动公开为DOM



这意味着

  var foo ='bar'; 

类似于

  window.foo ='bar'; 

这意味着您可以阅读任何的全局范围 window 对象可以获得一个引用。这里我们也可以暗示,使用窗口隐式。即使你没有明确地键入窗口,它也在那里。



由于框架本身也是自动公开为DOM当前窗口的属性对象,这意味着您也可以访问任何其他框架的窗口对象。



窗口属性包含 window 该窗口的父对象(如果有的话)。由于iframe绝对有一个父窗口,所以我输入的所有这些东西都归结为这个

  //设置全局变量父代全局范围中的'foo'
parent.foo ='bar';


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.

Does anyone know how to do this?

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');
    }
});

解决方案

Variables in the global scope are auto-exposed as DOM properties of their containing window object.

This means that

var foo = 'bar';

is analogous to

window.foo = 'bar';

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.

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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆