Web(html)编程中 document.write() 和document.writeln() 使用注意事项

最近几天,项目中编程需要绘制一个表示类型的树状结构。使用的是一个开源的javascript包 dtree ,用它的好处,主要是里面有两个函数,完全折叠和完全展开。感兴趣的朋友可以到这地方去下载:http://destroydrop.com/javascripts/tree/ 。如果仅仅只是一些链接,可以选择很多其他的javascript tree。我需要从数据库读取记录,利用递归来填充树状结构。但是在绘制最后形成的树时候,在使用document.write()时候,页面报错误:变量未定义,于是显示结果不正确。最后搜索 document.wrtie(),得知是这个地方出错的。具体原因如下:

在文档已经完成导入的时候,你不因该在当前文档中使用write() 或者writeln()方法,除非你第一次调用这个打开方法,因为这个方法会清除当前文档的window和擦除所有变量。

一般情况,不必使用document.open()方法打开文档,然为write() 方法将为自动打开文件和擦除内容。当方法write执行完毕后,你必须使用document.close() 方法关闭文档。由于换成的原因 有些浏览器write方法执行后,不能完全的显示,必须在关闭后才能完全显示。

英文原文:

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.  
   
  In   general,   it   is   not   necessary   to   open   the   document   using   the   document.open   method,   since   the   document.write   method   will   automatically   open   the   file   and   discard   (erase)   the   contents.   However,   after   the   write   is   complete,   you   need   to   close   the   document   by   using   the   document.close   method.   In   some   browsers,   the   results   of   the   write   may   not   be   completely   displayed,   due   to   buffering,   until   the   close   occurs.

网上其他人实例:

在下面代码中为什么只执行了一次,显示结果为1.如果将document.write改为文本框显示就可以得到0到9的循环出现?

<script   language="javascript">   
  var   k=0;   
  function   show()   
  {   
  document.write(k);   
  k++;   
  if(k==9)   
  {k=0;}   
  setTimeout(show,200);   
  }   
  </script>       
  <body>   
  <script   language="javascript">   
  show();   
  </script>   
  </body>   
  </html>  

当你调用document.write后你的那段程序就不存在了。有些地方直接使用document.innerHTML来实现。

 

posted @ 2009-06-15 17:28  蜀山剑侠  阅读(3480)  评论(5)    收藏  举报