上篇文章(DOM中获得对象的方法)中提到document的三个方法:getElementById(),getElementsByName() ,getElementsByTagName() .
在该文中再来看看document对象的其他方法:
write()方法:该方法用于向文档写入 HTML 表达式或文本。
代码
< html xmlns = " http://www.w3.org/1999/xhtml " >
< head >
< title > test </ title >
</ head >
< body >
document.write( " <b>Hello World!</b> " );
</ script >
</ body >
</ html >
writeln()方法:该方法与 write() 方法作用相同,外加可在每个表达式后输出一个换行符。
但要在<PRE> 标签中这个换行符才能被正确输出,否则被解析为一空格。
open() 方法:可打开一个新文档,并擦除当前文档的内容。(注意不要和window.open()混淆)
语法:document.open(mimetype,replace)
参数 | 描述 |
---|---|
mimetype | 可选。规定正在写的文档的类型。默认值是 "text/html"。 |
replace | 可选。当此参数设置后,可引起新文档从父文档继承历史条目。 |
该方法将擦除当前 HTML 文档的内容,开始一个新的文档,新文档用 write() 方法或 writeln() 方法编写。
重要事项:调用 open() 方法打开一个新文档并且用 write() 方法设置文档内容后,必须记住用 close 方法关闭文档,并迫使其内容显示出来。
注释:属于被覆盖的文档的一部分的脚本或事件句柄不能调用该方法,因为脚本或事件句柄自身也会被覆盖。
例一:
< head >
< script type ="text/javascript" >
function createNewDoc()
{
var newDoc = document.open( " text/html " , " replace " );
var txt = " <html><body>Learning about the DOM is FUN!</body></html> " ;
newDoc.write(txt);
newDoc.close();
}
</ script >
</ head >
< body >
< input type ="button" value ="Write to a new document"
onclick ="createNewDoc()" >
</ body >
</ html >
例二:
< head >
< script type ="text/javascript" >
function winTest()
{
var txt1 = " This is a new window. " ;
var txt2 = " This is a test. " ;
win.document.open( " text/html " , " replace " );
win.document.writeln(txt1);
win.document.write(txt2);
win.document.close();
}
</ script >
</ head >
< body >
< script type ="text/javascript" >
var win = window.open( '' , '' , ' width=200,height=200 ' );
winTest();
</ script >
</ body >
</ html >
close() 方法:可关闭一个由 document.open 方法打开的输出流,并显示选定的数据。
该方法将关闭 open() 方法打开的文档流,并强制地显示出所有缓存的输出内容。如果您使用 write() 方法动态地输出一个文档,必须记住当你这么做的时候要调用 close() 方法,以确保所有文档内容都能显示。一旦调用了 close(),就不应该再次调用 write(),因为这会隐式地调用 open() 来擦除当前文档并开始一个新的文档。