Phương thức HTML DOM Document write()
- ຫົວຂໍ້ໜ້າຫນື່ງເທີມ URL
- ຫົວຂໍ້ໜ້າຫນື່ງ writeln()
- ກັບຄືນລະດັບກ່ວານີ້ Documents DOM HTML
Định nghĩa và cách sử dụng
write()
Phương thức này ghi trực tiếp vào luồng tài liệu (HTML) mở.
Cảnh báo
write()
Khi sử dụng phương thức này trên tài liệu đã được tải, nó sẽ xóa tất cả HTML hiện có.
write()
Phương thức này không thể được sử dụng trong XHTML hoặc XML.
Lưu ý:write()
Phương thức này thường được sử dụng để ghi vào luồng đầu ra được mở bởi phương thức open(). Xin xem ví dụ dưới đây.
Xin xem thêm:
Cách sử dụng phương thức Document open()
实例
例子 1
Đưa văn bản trực tiếp vào đầu ra HTML:
document.write("Hello World!");
例子 2
Đưa HTML element trực tiếp vào đầu ra HTML:
document.write("<h2>Sà-là-sà-pà-rì!</h2><p>Làt sà-pà-rì!</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 |
ການສະໜັບສະໜູນ | ການສະໜັບສະໜູນ | ການສະໜັບສະໜູນ | ການສະໜັບສະໜູນ | ການສະໜັບສະໜູນ | ການສະໜັບສະໜູນ |
- ຫົວຂໍ້ໜ້າຫນື່ງເທີມ URL
- ຫົວຂໍ້ໜ້າຫນື່ງ writeln()
- ກັບຄືນລະດັບກ່ວານີ້ Documents DOM HTML