HTML DOM Document write() methode
- Previous page URL
- Next page writeln()
- Go up one level HTML DOM Documents
Definitie en gebruik
write()
Deze methode schrijft direct naar de geopende (HTML) documentstroom.
Waarschuwing
write()
Deze methode verwijdert alle bestaande HTML wanneer deze wordt gebruikt op een al geladen document.
write()
Deze methode kan niet worden gebruikt in XHTML of XML.
Tip:write()
Deze methode wordt het meest gebruikt om uitvoer te schrijven die is geopend met de open() methode. Zie het voorbeeld hieronder.
Zie ook:
实例
例子 1
Schrijf tekst direct naar HTML-uitvoer:
document.write("Hello World!");
例子 2
Schrijf HTML-elementen direct naar HTML-uitvoer:
document.write("<h2>Hello World!</h2><p>Have a nice day!</p>");
例子 3
加载文档后使用 document.write() 删除所有现有的 HTML:
// 应该避免这种情况: function myFunction() { document.write("Hello World!"); }
例子 4
将日期对象直接写入 HTML 输出:
document.write(Date());
例子 5
打开一个输出流,添加一些 HTML,然后关闭输出流:
document.open(); document.write("<h1>Hello World</h1>"); document.close();
例子 6
打开一个新窗口并在其中写入一些 HTML:
const myWindow = window.open(); myWindow.document.write("<h1>New Window</h1>"); myWindow.document.write("<p>Hello World!</p>");
语法
document.write(exp1, exp2, exp3, ...)
参数
参数 | 描述 |
---|---|
exp1, exp2, exp3, ... |
可选。输出流。 允许多个参数,并将按出现的顺序附加到文档中。 |
返回值
无。
write() 与 writeln() 的差别
writeln() 在每条语句后添加换行符。write() 不会。
实例
document.write("Hello World!"); document.write("Have a nice day!"); document.write("<br>"); document.writeln("Hello World!"); document.writeln("Have a nice day!");
注意
在 HTML 中使用 writeln() 是没有意义的。它仅在写入文本文档 (type=".txt") 时有用。HTML 中会忽略换行符。
如果您希望在 HTML 中换行,你必须使用段落或 <br>
:
例子 1
document.write("Hello World!"); document.write("<br>"); document.write("Have a nice day!");
例子 2
document.write("<p>Hello World!</p>"); document.write("<p>Have a nice day!</p>");
浏览器支持
所有浏览器都支持 document.write
:
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Support | Support | Support | Support | Support | Support |
- Previous page URL
- Next page writeln()
- Go up one level HTML DOM Documents