在javascript中将回调函数设置为新窗口 [英] Set a callback function to a new window in javascript

查看:198
本文介绍了在javascript中将回调函数设置为新窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个简单的方法来设置一个回调函数到一个在javascript中打开的新窗口?我想从新窗口运行父的一个功能,但我想让父能够设置这个特定的函数的名称(所以它不应该硬编码在新的Windows页面)。

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).

例如在父母中有:

function DoSomething { alert('Something'); }
...
<input type="button" onClick="OpenNewWindow(linktonewwindow,DoSomething);" />

在子窗口中,我想要:

<input type="button" onClick="RunCallbackFunction();" />


$ b <和 RunCallbackFunction 函数。我虽然将函数的名称作为查询参数发送到新窗口(服务器端脚本在生成的孩子的HTML中生成相应的函数调用),但是我想是否有另一个或更好的方法来完成

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.

纯JavaScript,服务器端解决方案和jQuery(或其他框架)都是欢迎的。

Pure javascript, server side solutions and jQuery (or other frameworks) are all welcomed.

推荐答案

更新评论:如果您通过 window.open() 然后在您的子页面中可以设置函数在子元素中只是一个指向父函数的引用,因此在子页面中有这样的引用:

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:

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.

这篇关于在javascript中将回调函数设置为新窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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