Metode HTML DOM Document write()
- Halaman sebelumnya URL
- Halaman berikutnya writeln()
- Kembali ke tingkat atas Dokumen DOM Documents
Definisi dan penggunaan
write()
Metode ini akan menulis langsung ke aliran dokumen (HTML) yang dibuka.
Peringatan
write()
Metode ini akan menghapus semua HTML yang ada saat digunakan di dokumen yang telah dimuat.
write()
Metode ini tidak dapat digunakan dalam XHTML atau XML.
Petunjuk:write()
Metode paling sering digunakan untuk menulis aliran output yang dibuka oleh metode open(). Lihat contoh di bawah ini.
Lihat pula:
实例
例子 1
Tulis teks langsung ke output HTML:
document.write("Hello World!");
例子 2
Tulis elemen HTML langsung ke output HTML:
document.write("<h2>Selamat Datang Dunia!</h2><p>Berikan hari yang bagus!</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 |
Dukungan | Dukungan | Dukungan | Dukungan | Dukungan | Dukungan |
- Halaman sebelumnya URL
- Halaman berikutnya writeln()
- Kembali ke tingkat atas Dokumen DOM Documents