0

我想从弹出窗口的子窗口访问父窗口的控件,例如:

  • Window1,Window2打开
  • Window2,Window3打开
  • Window3,Window2打开

现在我需要从 Window2 访问 Window1 的控件,以防从 Window3 打开 Window2,我该怎么做?

我尝试使用window.opener.getElementById(),但window.opener.opener.getElementById()我在这里很困惑!

编辑:

Window1 中打开 Window2 的代码

window.open('window2');

Window2 中打开 Window3 的代码

window.location.href = 'Window3';

在 Window3 中打开 Window2 的代码:

window.open('window2');

在此处输入图像描述

4

2 回答 2

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;
}
于 2013-01-09T08:12:56.947 回答
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);
}

上面应该总是返回基本打开器,只要它在每个新打开的窗口上执行一次,就在那个窗口被创建之后(并且整个窗口链在那个时候仍然存在)。

显然,如果基本窗口曾经关闭过,您就会遇到问题;)

更新

抱歉,我认为以上内容很清楚,我想这是因为您已经处理了 Windows 之间的大量相互通信——但如果不是,则不是:) 无论如何,我添加了注释来解释代码并添加了使用信息以使事情更清晰.

放置以下内容,以便将其加载到将要打开的每个窗口中。

<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');
于 2013-01-09T07:58:07.920 回答