document.write空白页面

时间:2018-02-23 15:41:30

标签: javascript html

我正在尝试运行此代码以从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>

我不知道怎么做,但我一直在看一个空白的窗口。有什么帮助吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

您的段落没有id

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

当您致电document.getElementById(undefined)时,您会获得null

当您阅读null.innerHTML时,会收到错误。

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

这就像从你手中的书中读出Dewey Decimal代码,这样你就可以去它所生活的架子,这样你就可以阅读它。

另外,请勿使用item(),只需将节点列表视为数组。

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