JS 中document.write()的用法和清空的原因浅析(2)
由doucment.open()创建的文档流就可以由document.close()关闭,那么第二个document.write()输出的内容会覆盖掉第一个输出的内容。
异步引用外部JavaScript时,必须先运行document.open()清空文档,然后才能运行document.write(),参数写在body内容的开头。
如果不先运行document.open(),直接运行document.write(),则无效且Chrome有如下提示:

// asyncWrite.js
document.open();
document.write('<p>test</p>');
document.close();
<!-- asyncWrite.html -->
<!-- 运行前 -->
<body>
<script src="asyncWrite.js" async></script>
</body>
<!-- 运行后 -->
<body>
<p>test</p>
</body>
document.write()也能写入含有script标签的字符串,但是需要转义。写入的script标签中的内容会正常运行。
<!-- 运行前 -->
<script>
document.write('<script>document.write("<p>test</p>");<\/script>');
</script>
<!-- 运行后 -->
<script>
document.write('<script>document.write("<p>test</p>");<\/script>');
</script>
<script>document.write("<p>test</p>");</script>
<p>test</p>
document.write()可以传入多个参数。
<!-- 运行前 -->
<body>
<script>
document.write('<h2>multiArgument</h2>','<p>test</p>');
</script>
</body>
<!-- 运行后 -->
<body>
<script>
document.write('<h2>multiArgument</h2>','<p>test</p>');
</script>
<h2>multiArgument</h2>
<p>test</p>
</body>
总结
以上所述是小编给大家介绍的JS 中document.write()的用法和清空的原因浅析,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对黑区网络网站的支持!
