【问题标题】:access new window's DOM from the parent's javascript从父级的 javascript 访问新窗口的 DOM
【发布时间】:2014-12-19 20:59:13
【问题描述】:

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

<!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>

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

<!doctype html>

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

</head>

<body>

<p id="para">Old</p>
</body>
</html>

非常感谢!

【问题讨论】:

    标签: javascript


    【解决方案1】:

    在打开新的 HTML 页面之前,您必须使用 sessionStorage 才能将信息从一个页面更改/传递到另一个页面。

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案2】:

    您必须等待新窗口加载其内容。打开窗口后,内容不会立即可用。您可以使用窗口加载事件来了解它何时完成加载,然后您可以在该事件触发时修改其 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>
    

    【讨论】:

    • 但是没有用。现在,当我单击按钮时,我再也看不到新窗口了。
    • @HuiHao - 我的代码中有一个简单的错字。现在修好了。您应该能够在浏览器调试控制台中查看自己的简单语法错误。这是 Javascript 最基本的调试技术。如果您看不到基本的输入错误,这就像在黑暗中编码一样。
    • 我注意到之前的结尾是 ")" 和 ";"我纠正了他们。现在控制台不再抱怨,不再有语法错误。但是新信息仍然没有显示在新窗口中。它仍然显示“旧”文本。
    猜你喜欢
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多