宝哥软件园

JS中document.write()的用法及其清空的原因

编辑:宝哥软件园 来源:互联网 时间:2021-09-02

很多朋友可能都遇到过这样的情况,就是在使用document.write()函数向网页中写入内容时,文档中的原始内容会被清空,这对于初学者来说是一个问题。让我们介绍为什么会发生这种情况,当然也知道如何避免。

首先看一个代码示例:

!doctype HTML HTML Head metharset=' UTF-8 ' Title Document/Title Script Type=' text/JavaScript ' window . onload=function(){ Document . write('重访JavaScript ');}/script/head body div hello JavaScript/div/body/html从上面的代码可以看出,document.write()函数清空了原始文档内容,下面介绍一下出现这种情况的原因:

window.onload事件是在文档内容完全加载后执行事件处理功能。当然,文档流已经关闭。此时,执行doucment.writ()函数会自动调用document.open()函数创建新的文档流,写入新内容,然后通过浏览器显示,会覆盖原来的内容。但是,很多朋友还是有这样的疑问。为什么原始网页中的内容没有像以下情况一样被覆盖?代码如下:

!doctype html html head meta charset=' utf-8 ' title document/title script type=' text/JAVAScript ' document . write('重访JAVAScript ');/script/head body div hello JavaScript/div/body/html在上面的代码中,原始的文档内容并没有被清空,因为当前的文档流是由浏览器创建的,document.wirte()函数就在其中,也就是说执行这个函数时文档流并没有关闭,此时也不会调用document.open()函数来创建新的文档流,所以不会被覆盖。有些朋友可能会问为什么下面的方法还是不行。代码如下:

!DOCTYPE html html head meta charset=' utf-8 ' title document/title script type=' text/JavaScript ' document . close();Document.write('重访JAVAScript ');/script/head body div hello JAVAScript/div/body/html上面,document.close()用于关闭文档流。为什么原始内容不能被覆盖?不幸的是,文档流是由浏览器创建的,它没有手动关闭的权限。document.close()函数只能关闭document.open()函数创建的文档流。请看下面的代码示例:

!DOCTYPE html html head meta charset=' utf-8 ' title Document/title script type=' text/JavaScript '函数create(){ var new window=window . open(',' Document ',' _ blank ');new WiNDOW . document . write(' Hello JavaScript ');new WiNDOW . document . close();NewWindow.document.write('覆盖后输出');} window . onload=function(){ var obt=document . getelementbyid(' Bt ');obt . onclick=function(){ create();} }/script/head body div id=' print ' hello JavaScript/div input type=' button ' id=' Bt ' value=' view effect '/body/html由doucment.open()创建的文档流可以由document.close()关闭,然后第二个文档的输出. write()将覆盖第一个文档

异步引用外部JavaScript时,必须先运行document.open()清空文档,然后再运行document.write(),参数写在正文内容的开头。

如果不运行document.open(),直接运行document.write(),则无效,Chrome会有如下提示:

这里写图片描述

//AsyncWrite . jsdocument . open();document . write(' ptest/p ');document . close();asyncWrite.html!-运行前-body脚本src=' http : aasyncwrite . js ' async/script/body!-running-body ptest/p/body document . write()之后也可以写入带有脚本标记的字符串,但需要进行转义。书面脚本标签中的内容将正常工作。

!-运行前-编写文档脚本。编写('脚本文档。write(' ptest/p ');/script’);/脚本!-运行后-编写文档脚本。编写('脚本文档。write(' ptest/p ');/script’);/script脚本文档。write(' ptest/p ');/scriptptest/pdocument.write()可以传入多个参数。

!-运行前-正文脚本文档。write(' H2MultiArgument/H2 ',' ptest/p ');/脚本/正文!-运行后-正文脚本文档。write(' H2MultiArgument/H2 ',' ptest/p ');/脚本h2多参数/H2 ptest/p/车身总结

以上所述是小编给大家介绍的射流研究…中document.write()的用法和清空的原因浅析,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!

更多资讯
游戏推荐
更多+