在有window.onload的情况下,使用document.write()函数向网页中写内容的时候,会把文档中的原来的内容给清空。
<!DOCTYPE html
>
<html
>
<head
>
<meta charset
=" utf-8">
<title
></title
>
<script type
="text/javascript">
window
.onload=function(){
document
.write("张三");
}
</script
>
</head
>
<body
>
<div
>李四
</div
>
</body
>
</html
>
运行以上代码,可以看到document.write()函数将原来的文档内容清空了,出现这种情况的原因是: window.onload事件是在文档内容完全加载完毕再去执行事件处理函数,这个时候文档流已经关闭了,这个时候执行document.write()函数会自动调用document.open()函数创建一个新的文本流,并写入新的内容,在通过浏览器展现,这样就会覆盖原来的内容。所以html里的内容变成了“张三”。