从子窗口调用父窗口的 JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17095607/
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
Call JavaScript of parent window from child window
提问by David Bélanger
I have a calendar and when I click on a <td>
, a pop-up window appears so you can create your evenement for the date you selected. I want to add a feature.
我有一个日历,当我点击 a 时<td>
,会出现一个弹出窗口,以便您可以为您选择的日期创建晚间活动。我想添加一个功能。
When the user finishes creating the event, I want to send a JavaScript request to the parent page so I can refresh the calendar using AJAX. Basically, I want to call a function from the child, but the function is on the parent page.
当用户完成创建事件时,我想向父页面发送一个 JavaScript 请求,以便我可以使用 AJAX 刷新日历。基本上,我想从子页面调用一个函数,但该函数在父页面上。
On Google, I only found a script that can refresh the parent window – nothing about a “parent callback”. ? Is it even possible?
在谷歌上,我只找到了一个可以刷新父窗口的脚本——与“父回调”无关。? 甚至有可能吗?
P.S. The answer can be pure JS or jQuery, it doesn't matter. I'll keep looking in the meanwhile.
PS 答案可以是纯 JS 或 jQuery,没关系。与此同时,我会继续寻找。
回答by Michael Geary
What you're looking for is a reference to the window
that opened the popup window. Once you have that, you can call functions in that window, read and write variables in that window, or even manipulate its DOM.
您要查找的是对window
打开弹出窗口的的引用。一旦你有了它,你就可以在那个窗口中调用函数,在那个窗口中读写变量,甚至操作它的 DOM。
That reference is called opener
. It gives you the window
object for the window that opened the current window. For example, if you have a function in the original window like this:
该引用称为opener
. 它为您提供window
打开当前窗口的窗口的对象。例如,如果您在原始窗口中有这样一个函数:
function updateMe( data ) {
alert( data );
}
then in the popup window you could call it like this:
然后在弹出窗口中,您可以这样称呼它:
opener.updateMe( 'Hello!' );
Naturally, you need to make sure that updateMe()
is a global function in the original page. Or if you have some object in the original page and updateMe()
is a method of that object, you can still do it, as long as the object is global. e.g. in the host page:
当然,您需要确保这updateMe()
是原始页面中的全局函数。或者,如果您在原始页面中有某个对象并且updateMe()
是该对象的方法,您仍然可以这样做,只要该对象是全局的。例如在主机页面中:
var myObject = {
updateMe: function( data ) {
alert( data );
}
};
then in the popup you could do:
然后在弹出窗口中,您可以执行以下操作:
opener.myObject.updateMe( 'Hello!' );
Basically, as long as you could get to the object or function in the original page with window.whatever
, then in the popup you can simply change that to opener.whatever
.
基本上,只要您可以使用 访问原始页面中的对象或函数window.whatever
,然后在弹出窗口中您就可以简单地将其更改为opener.whatever
。