javascript document.innerHTML 设置整个文档的内容 [英] javascript document.innerHTML set content of whole document

查看:44
本文介绍了javascript document.innerHTML 设置整个文档的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 javascript 设置 innerHTML 或 HTML 文档的全部内容?

How can I set the innerHTML, or the whole content of an HTML document using javascript?

例如我的文档看起来像这样:

For example my document would look like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="Content-language" content="en"/>
    <title>Webpage Generator</title>
    <script type="text/javascript">
    var newDocument = "&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; \n\t&quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;\n&lt;html&gt;\n&lt;head&gt;\n\t&lt;title&gt;Greetings!&lt;/title&gt;\n&lt;/head&gt;\n&lt;body&gt;\n\t&lt;p&gt;Howdy!&lt;/p&gt;\n&lt;/body&gt;\n&lt;/html&gt;";
    document.innerHTML = newDocument;
    </script>
</head>
<body>
</body>
</html>

但浏览器会加载以下 HTML:

But the browser would load the following HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Greetings!</title>
</head>
<body>
    <p>Howdy!</p>
</body>
</html>

推荐答案

如果你不想使用innerHTML,你可以使用document.write(newDocument);.

If you don't want to use innerHTML you could use document.write(newDocument);.

如果文档尚未完全加载,您还需要放入 document.open()(感谢 bažmegakapa).

If the document hasn't completely loaded, you'll need to put document.open() as well (thanks bažmegakapa).

这篇关于javascript document.innerHTML 设置整个文档的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆