16.2 基本Document方法
Document对象支持5个方法,用于控制向文档的输出。这5个方法是:clear( )、close( )、open( )、write( )与writeln( )。在本书中,经常使用document.write( )来向文本中输出字符串。本节介绍这些方法的使用。
16.2.1 document.write( )与document.writeln( )
这两个方法都向文档中输入字符串,主要区别是:document.writeln( )方法会在其输出结果后添加一个换行符(“\n”),而document.write( )方法则不会。然而,在XHTML中,除非在个别情况下(例如<pre>标签或者在<textarea>中),回车或换行符都会被忽略。因此,一般不会感觉到二者的区别。在代码16.8中,使用<pre>标签演示了二者的区别。
代码16.8 document.write( )与document.writeln( ):16.8.htm
<html>
<head><title>document.write()与document.writeln()</title></head>
<body>
<h1>document.write()与document.writeln()</h1><p>
<pre>
<script type="text/javascript">
<!--
//这一行输出后不会换行
document.write("尽管在pre标签内,但本行结尾不会添加换行符。");
//这一行输出后将会换行
document.writeln("而这一行的结尾会添加一个换行符");
//这一行输出后同样会换行
document.writeln("现在已经换行。");
//这一行中,由于使用了<br>,所以会在此处换行
document.write("总是可以使用 <br> 元素<br>在HTML中进行换行。");
//-->
</script>
</pre>
</body>
</html>
上面代码的运行结果如图16.14所示。

图16.14 运行结果
由于document.write( )与document.writeln( )都可以输出字符串,并可以使用<br>进行换行控制,因此,不必每输出一行就写一个document.write( )或document.writeln( )语句,可以使用代码16.9中的方法,通过字符串连接将结果一起输出。
代码16.9 字符串连接输出:16.9.htm
<html>
<head><title>字符串连接输出</title></head>
<body>
<h1>字符串连接输出</h1><p>
<script type="text/javascript">
<!--
var str = ""; //定义一个空字符串
str += "This is a very long string."; //向其中添加一句话
//添加XHTML元素标签
str += "It has entities like © as well as <b>XHTML</b> tags.";
//添加XHTML元素标签
str += "We can even include <pre> various special characters like";
//添加两种转义字符,实现跳格和换行
str += "\t \t tabs or even newlines \n \n in our string</pre>";
str += "but remember the rules of XHTML may override \t\t\n our efforts";
document.write(str); //结果输出
//-->
</script>
</body>
</html>
上面代码运行后的显示结果如图16.15所示。

图16.15 显示结果
16.2.2 其他方法
Document对象的其他方法的功能从其名称即可理解:clear( )用来清除一个文档中的内容,而close( )和open( )则分别关闭或打开一个文档,以关闭写入或准备写入。在现代JavaScript浏览器中,不支持clear( )方法,并且,当使用document.write( )对文档写入完毕后,对文档的写入即关闭。代码16.10是使用close( )和open( )的例子。
代码16.10 document.close( )和document.open( ):16.10.htm
<html>
<head><title>document.close()和document.open()</title></head>
<body>
<h1>document.close()和document.open()</h1><p>这是原来的窗口
<script type="text/javascript">
<!--
//打开一个新窗口,其宽、高都为300像素
var myWindow = window.open("","newwin", "height=300,width=300");
myWindow.document.open(); //打开写入
//写入HTML页面头
myWindow.document.write("<html><head><title>Test</title></head><br>");
//写入HTML页面内容
myWindow.document.write("<body><h1>Hello!</h1>
<p>这是新打开的窗口</body></html>");
myWindow.document.close(); //关闭输入
//-->
</script>
</body>
</html>
上面的代码运行后,在原来窗口的基础上再打开一个新窗口,并在新窗口的文档中写入一段HTML代码。这样在新窗口中就会显示HTML代码的结果。原窗口与新窗口的显示效果如图16.16所示。

图16.16 显示效果







