【问题标题】:document.write blank pagedocument.write 空白页
【发布时间】:2018-02-23 15:41:30
【问题描述】:

我正在尝试运行此代码以从我的 HTML 代码中的段落中获取元素并显示:

<!DOCTYPE html>
<html>
<body>

<p>This is a p element<br>

This is also a p element.<br>

This is also a p element - Click the button to change the background color of all p elements in this document.</p>

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

<script>
    function myFunction() {
        win = window.open();
        win.document.open();
        var x = document.getElementsByTagName("p");
        for (var i = 0; i < x.length; i++) {
            win.document.write(document.getElementById(x.item(i).id).innerHTML);
        }
    }
</script>

</body>
</html>

我不知道怎么做,但我总是得到一个空白窗口。有什么帮助吗?

谢谢。

【问题讨论】:

  • document.write 写在页面上,你永远不想使用它,因为它很糟糕而且过时了
  • @SterlingArcher — 在没有文档的新窗口中调用document.write。问题是文档是blank,而不是现有内容被新内容覆盖。
  • @SterlingArcher 正确使用,有很多/一些可能的应用(例如stackoverflow.com/a/1014251/402037

标签: javascript html


【解决方案1】:

您的段落没有id

因此,当您阅读其id 属性时,您会得到undefined

当您拨打document.getElementById(undefined) 时,您会收到null

当你阅读null.innerHTML时,你会得到一个错误。


已经拥有该元素。不要试图从元素中获取ID,以便您可以获取元素。

这就像从你手中的书中阅读杜威十进制代码,这样你就可以去它所在的书架上阅读它。

另外,不要使用item(),只需将节点列表视为数组即可。

win.document.write(x[i].innerHTML);

【讨论】:

  • 是的,完美!谢谢,但我的问题是我添加了一个对齐样式,它没有反映在新打开的窗口中!这是我的主要问题,知道如何解决吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-30
  • 2013-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-20
相关资源
最近更新 更多