我想从popoup的孩子访问父窗口的控件,如:
Window1
开始,Window2
已打开Window2
开始,Window3
已打开Window3
开始,Window2
已打开现在我需要从Window2访问Window1的控件,以防从Window3打开Window2时,我该怎么办?
我试图使用window.opener.getElementById()
和window.opener.opener.getElementById()
我感到很困惑!
修改
打开Window2的Window1中的代码:
window.open('window2');
打开Window3的Window2中的代码:
window.location.href = 'Window3';
在Window3中打开Window2的代码:
window.open('window2');
答案 0 :(得分:1)
由于您再次使用窗口,原始开启者值丢失
你必须使用window.name来识别窗口
window3 > window.open(url, "window2",.....);
window1 > window.open(url, "window2",.....);
您可以使用
命名/重命名窗口window.name = "window3";
你也可以使用这个
function getOpenerWindowByName(name)
{
var w = window;
while(w = w.opener) if(w.name === name) return w;
return null;
}
答案 1 :(得分:0)
您可以向后扫描window.opener
链:
function getBaseOpener(win){
var opener;
do {
/// check to see if our storage property has been set, if so use it
/// this gets around the problem that the window.opener chain may have
/// been broken.
if ( win.baseOpener ) {
opener = win.baseOpener;
break;
}
/// for each window.opener we find scan backwards until we find a
/// window that has no window.opener. This should be our main window.
} while( (opener = win.opener) && (win = opener) );
/// return the result and store it for next time, this will prevent
/// problems if any of our openers are ever closed.
return (win.baseOpener = opener);
}
上面应该总是返回基本开启器,只要在创建该窗口之后在每个新打开的窗口上执行一次(并且整个窗口链在该点仍然存在)。
显然,如果基本窗口关闭,则会出现问题;)
放置以下内容,以便它将加载到您将打开的每个窗口中。
<script>
function getBaseOpener(win){
var opener;
do {
if ( win.baseOpener ) {
opener = win.baseOpener;
break;
}
} while( (opener = win.opener) && (win = opener) );
return (win.baseOpener = opener);
}
/// this first execution is important, it creates the baseOpener
/// property that will keep our link to the main window even
/// if our parents have been closed and reopened later on.
var mainWindow = getBaseOpener(window);
</script>
然后,如果您需要获取基本窗口,请在代码中的任何位置使用以下内容:
mainWindow
或再次运行getBaseOpener:
getBaseOpener(window)
这应该总是返回基本/主窗口(窗口1) - 除非从基本窗口本身执行...它将返回undefined
。
如果您希望使用getElementById
,则需要访问以下文档:
mainWindow.document.getElementById('element_id');