日期:2014-05-16  浏览次数:20333 次

document.write语句,为什么有时候会把之前的内容清除掉呢?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script language="javascript">
<!--
function aa(){
document.write("AAA!");
}
//-->
</script>
</head>
<body>
<script language="javascript">
aa();
aa();
</script>
<input type="button" name="Submit" value="按钮" onclick="aa();"/>
</body>
</html>
在上面的程序中,直接调用两次aa()函数,可以输出两行“AAA”,为什么单击按钮去调用aa()函数,就会把之前的内容清除掉呢?

------解决方案--------------------
是这样的,你可以将输出结果写入到一个层里面
div.innerHTML=~~~来显示
------解决方案--------------------



[个人意见,仅供参考] 

单击按钮去调用aa()函数的时候,document对象已经完全载入解析完毕了,
这是再使用document.write就相当于修改document对象的内容(也就是整个页面的内容)
所以,整个页面的内容就被清除了


'----------------------------------------
'个人签名,与本贴无关。
'瘦猴网络(www.sohoiii.com)
'----------------------------------------
------解决方案--------------------
同意楼上的,应该是因为body还未完全加载之前,document.write就会直接写入,但当整个页面加载完毕,也就是body加载完了,document.write就是改写整个body里的内容,应该是这样吧。
------解决方案--------------------
好好看手册!!!

write Method
Writes one or more HTML expressions to a document in the specified window. 

Syntax
document.write(sText)

Remarks
You should not use the write or writeln methods on the current document after the document has finished loading unless you first call the open method, which clears the current document's window and erases all variables.