document.write() 和writeln()方法注意事项

BOM的document对象最常用的方法之一是write()或它的兄弟方法writeln()。这两个方法都接受一个参数,即要写入文档的字符串。如您所料,它们之间唯一的区别是writeln()方法将在字符串末尾加一个换行符(n)。
   这两个方法都会把字符串的内容插入到调用它们的位置。这样浏览器就会像处理页面中的常规HTML代码一样处理这个文档字符串。考虑下面的页面:

   <html>
      <head>
         <tltle>Document Write Example</title>
      </head>
      <body>
         <h1><script type="text/javascript">document.write("this is a test")</script></h1>
      </body>
   </html>

   该页面在浏览器中看来与下面的页面一样:
   <html>
      <head>
         <title>Document Write Example</title>
      </head>
      <body>
         <h1>this is a test</h1>
      </body>
   </html>
   可以使用这种功能动态地引入外部JavaScript文件。例如:

   <html>
      <head>
         <title>Document Example</title>
         <script type="text/javascript">
            document.write("<script type="text/javascript" src="external.js">"+"</src"+"ipt");
         </script>
      </head>
      <body>
      </body>
   </html>

   这段代码在页面上写了一个<script/>标鉴,将使浏览器像常规一样载入外部JavaScript文件。注意字符串"</script>"被分成两部分("</src"和"ipt>")。

   这是必要的,因为每当浏览器遇到</script>,它都假定其中的代码块是完整的(即使它出现在JavaScript字符串中)。假设前面的例子未把"</script>”分成两部分:

   <html>
      <head>
         <title>Document Example</title>
            <script type="text/javascript">
               docunment.write("<script type="text/javascript" src="external.js">"+"</script>");     //this will cause a problem
      </head>
      <body>
      </body>
   </html>

   浏览器显示如下网页:
   <html>
      <head>
         <title>Document Example</title>
            <script type="text/javascript">
                  document.write("<script type="text/javascript" src="external.js">"
            </script>
            </script>
      </head>
      <body>
      </body>
   </html>
  
   可以看到,忘记把字符串"</script>"分成两部分引起了严重的混乱。首先,在<script/>标签内有个语法错,因为document write()的调用漏掉了闭括号。其次,有两个</script>标签。这就是在使用document.Write()方法把<script/)标签写入页面时一定要把"</script>"字符串分开的原因。

   记住,要插入内容属性,必须在完全载入页面前调用write()和writeln()方法。如果任何一个方法是在页面载入后调用的,它将抹去页面的内容,显示指定的内容。

   与write()和witeln()方法密切相关的是open()和close()方法。open()方法用于打开已经载入的文档以便进行编写,close()方法用于关闭open()方法打开的文档,本质上是告诉它显示写入其中的所有内容。通常把这些方法结合在一起,用于向框架或新打开的窗口中写入内容,如下所示:

   var oNewWin=window.open("about:blank","newwindow","height=150,width=300,top=10,left=10,resizable=yes");

   oNewWin.document.open();
   oNewWin.document.write("<html><head><title>New Window</title></head>");
   oNewWin.document.write("<body>This is a new window!</body></html>");
   oNewWin.document.close();

   这个例子打开空白页(使用本地的"about:blank"URL),然后写入新页面。要正确实现这一操作,在调用write()前,先调用open()方法。写完后,调用close()方法完成显示。当您想显示无需返回服务器的页面时,这种方法非常有用。

 
 
原文地址:https://www.cnblogs.com/htys/p/3947708.html