繁体   English   中英

document.write空白页

[英]document.write blank page

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

我不知道如何,但是我一直在空白。 有什么帮助吗?

谢谢。

您的段落没有id

因此,当您读取其id属性时,将得到undefined

调用document.getElementById(undefined)您将获得null

当您读取null.innerHTML ,会出现错误。


已经有了元素。 不要尝试从元素获取ID,以便可以获取元素。

这就像从您手中的书中读取Dewey十进制代码,以便可以转到其上的书架上以进行阅读。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM