如何使用javascript从孩子的孩子访问父母的控件?

时间:2013-01-09 07:43:24

标签: javascript parent-child

我想从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');

enter image description here

2 个答案:

答案 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');