2012-07-09 173 views
1

您好,非常感谢您阅读我的文章。Javascript getElementById从父窗口到子窗口

以下是我基本上要做到:

  • 在第一个HTML页面( “parent.html”),有一个按钮;

  • 当用户点击该按钮弹出一个新窗口了(“child.html”)

  • ,并在子窗口中的“格”元素的内容进行更新。

“Firefox”和“Chrome”下的最终操作不成功。

parent.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>Parent window document</title> 
    </head> 
    <body> 
    <input 
    type="button" 
    value="Open child window document" 
    onclick="openChildWindow()" /> 

    <script type="text/javascript"> 
    function openChildWindow() 
    { 
     var s_url  = "http://localhost:8080/projectroot/child.html"; 
     var s_name = "ChildWindowDocument"; 
     var s_specs = "resizable=yes,scrollbars=yes,toolbar=0,status=0"; 
     var childWnd = window.open(s_url, s_name, s_specs); 
     var div  = childWnd.document.getElementById("child_wnd_doc_div_id"); 
     div.innerHTML = "Hello from parent wnd"; 
    } 
    </script> 
    </body> 
</html> 

child.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>Parent window document</title> 
    </head> 
    <body> 
    <div id="child_wnd_doc_div_id">child window</div> 
    </body> 
</html> 
  • IE9 =>它的工作原理。

  • Firefox 13.0.1 =>它不起作用。错误消息:“div为空”。

  • Chrome 20.0.1132.47 m =>不起作用。

你明白这种行为吗?

你能帮我在这三种情况下工作吗?

谢谢,最好的问候。

回答

1

我认为窗口/文档在您尝试访问它的元素时未加载。你可以做类似

childWnd.onload = function() { 
    var div  = childWnd.document.getElementById("child_wnd_doc_div_id"); 
    div.innerHTML = "Hello from parent wnd"; 
} 

你也可以看看mdn doc


更好的解决问题的方法可能是对“孩子”进行更改。您可以使用window.opener访问父窗口。但是你应该记住父窗口可以关闭,所以你应该考虑某种类型的本地存储(例如cookie)。

+0

你好,非常感谢你的回答。 这确实解决了“Firefox”和“Chrome”的问题,但它不再与“IE”一起工作... 此致敬礼。 – 2012-07-10 08:01:11

+0

看来,window.open返回之前,在IE中创建窗口。这是一个可能的解决方案http://flightschool.acylt.com/devnotes/window-open-onload-window-events/,但我会尽力找到/做出更好的解决方案(明天也许......)。 – bliof 2012-07-10 08:40:09

+0

再次感谢您的答复。 我跟着你指向我的链接(带有“超时”技巧的链接(http://flightschool.acylt。com/devnotes/window-open-onload-window-events /)),我用我自己定制的代码,现在确实可以在我的第一篇文章中提到的三种浏览器中工作。但它并不完全令人满意(即“超时”技巧)......所以我当然会对“更好”的解决方案感兴趣。 – 2012-07-10 14:01:22