Javascript 在javascript中将回调函数设置为新窗口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2797560/
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
Set a callback function to a new window in javascript
提问by SztupY
Is there an easy way to set a "callback" function to a new window that is opened in javascript? I'd like to run a function of the parent from the new window, but I want the parent to be able to set the name of this particular function (so it shouldn't be hardcoded in the new windows page).
有没有一种简单的方法可以将“回调”函数设置为在 javascript 中打开的新窗口?我想从新窗口运行父级的函数,但我希望父级能够设置此特定函数的名称(因此不应在新窗口页面中对其进行硬编码)。
For example in the parent I have:
例如在父母我有:
function DoSomething { alert('Something'); }
...
<input type="button" onClick="OpenNewWindow(linktonewwindow,DoSomething);" />
And in the child window I want to:
在子窗口中,我想:
<input type="button" onClick="RunCallbackFunction();" />
The question is how to create this OpenNewWindowand RunCallbackFunctionfunctions. I though about sending the function's name as a query parameter to the new window (where the server side script generates the appropriate function calls in the generated child's HTML), which works, but I was thinking whether there is another, or better way to accomplish this, maybe something that doesn't even require server side tinkering.
问题是如何创建 thisOpenNewWindow和RunCallbackFunction函数。我虽然将函数的名称作为查询参数发送到新窗口(服务器端脚本在生成的孩子的 HTML 中生成适当的函数调用),但我在想是否有另一种或更好的方法来完成这,也许甚至不需要服务器端修补的东西。
Pure javascript, server side solutions and jQuery (or other frameworks) are all welcomed.
纯 javascript、服务器端解决方案和 jQuery(或其他框架)都受到欢迎。
回答by Nick Craver
Updated for comments:If you're opening your window via window.open()then in your child page you can set a function in the child to just be a reference pointing to a parent function, so have this in the child page:
更新评论:如果您通过window.open()then 在您的子页面中打开您的窗口,您可以在子页面中设置一个函数作为指向父函数的引用,因此在子页面中设置它:
var RunCallbackFunction = function() { }; //reference holder only
Then in your parent (opener), set that function when that child window loads, like this:
然后在您的父窗口(开启程序)中,在子窗口加载时设置该函数,如下所示:
//random function you want to call
function myFunc() { alert("I'm a function in the parent window"); }
//to actually open the window..
var win = window.open("window.html");
win.onload = function() { win.RunCallbackFunction = myFunc; };
This assigns the function in your parent to now be the target of that child...and you can point each child to a different function if you wish, they're all independent.
这会将您的父级中的函数指定为该子级的目标……如果您愿意,您可以将每个子级指向不同的函数,它们都是独立的。
回答by kayz1
var newWindow = window.open(window.location.origin);
newWindow.onload = function() {
$(newWindow.document.body).addClass('new-window-body-class');
};

