在javascript中设置新窗口的回调函数
有没有一种简单的方法可以为在 javascript 中打开的新窗口设置“回调”函数?我想从新窗口运行父级的函数,但我希望父级能够设置此特定函数的名称(因此不应在新窗口页面中对其进行硬编码)。
例如,在父窗口中我有:
function DoSomething { alert('Something'); }
...
<input type="button" onClick="OpenNewWindow(linktonewwindow,DoSomething);" />
在子窗口中我想要:
<input type="button" onClick="RunCallbackFunction();" />
问题是如何创建此 OpenNewWindow 和 RunCallbackFunction 函数。我想将函数的名称作为查询参数发送到新窗口(服务器端脚本在生成的子级 HTML 中生成适当的函数调用),这是可行的,但我在想是否有另一种或更好的方法来完成这,也许甚至不需要服务器端修补。
纯 JavaScript、服务器端解决方案和 jQuery(或其他框架)都受到欢迎。
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).
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 OpenNewWindow
and RunCallbackFunction
functions. 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.
Pure javascript, server side solutions and jQuery (or other frameworks) are all welcomed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更新评论:如果您通过
window 打开窗口.open()
然后在你的子页面中,你可以在子页面中设置一个函数作为指向父函数的引用,所以在子页面中有这个:然后在你的父页面中(opener ),在子窗口加载时设置该函数,如下所示:
这将您的父窗口中的函数分配为该子窗口的目标...如果您愿意,您可以将每个子窗口指向不同的函数,它们都是独立的。
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:Then in your parent (opener), set that function when that child window loads, like this:
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.
很抱歉提出一个老问题,但我需要做类似的事情,并且觉得有必要分享一个我满意的解决方案。
父项:
子项:
来源(带有一些安全警告和详细文档):
https://developer.mozilla.org/docs/Web/API/Window/打开
sorry to up an old question but I needed to do something similar and felt the need to share a solution I'm happy with.
Parent:
Child:
Source (with some security warnings and detailed doc):
https://developer.mozilla.org/docs/Web/API/Window/open