从父母的javascript访问新窗口的DOM

时间:2014-10-24 03:08:07

标签: javascript

我试图点击一个按钮,并调用该函数使其打开一个已经存在的新窗口,使用window.open()方法,同时,我想更改新窗口&#39 ; s内容使用document.getElementById(' para')。innerHTML =" New&#34 ;;但我无法访问和更改内容。



<!DOCTYPE html>
<html>
<body>

<p>I want to click on the button and opens a new window, can change the new window's text "old"to the word "New", but I can't access the new window</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var myWindow = window.open("newWindow.html", "MsgWindow", "width=200, height=100");
    myWindow.document.getElementById('para').innerHTML="New";
}
</script>

</body>
</html>
&#13;
&#13;
&#13;

下面是我尝试访问和操作的新窗口

&#13;
&#13;
<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">

</head>

<body>

<p id="para">Old</p>
</body>
</html>
&#13;
&#13;
&#13;

非常感谢!

1 个答案:

答案 0 :(得分:1)

您必须等待新窗口加载其内容。打开窗口后,内容将无法立即显示。您可以使用窗口加载事件来了解它何时完成加载,然后您可以在该事件触发时修改其DOM。

<script>
function myFunction() {
    var myWindow = window.open("newWindow.html", "MsgWindow", "width=200, height=100");
    myWindow.addEventListener("load", function() {
        myWindow.document.getElementById('para').innerHTML="New";
    });
}
</script>