Output JavaScript
JavaScript tidak menyediakan mana-mana fungsi cetak atau pameran binaan.
JavaScript boleh
- gunakan
window.alert()
menulis ke bingkai amaran - gunakan
document.write()
menulis ke output HTML - gunakan
innerHTML
menulis ke elemen HTML - gunakan
console.log()
menulis ke konsol pemeriksaan pelayar
gunakan innerHTML
Untuk mengakses elemen HTML, JavaScript boleh digunakan document.getElementById(id)
Kaedah.
id
Atribut menentukan elemen HTML. Atribut innerHTML menentukan kandungan HTML:
实例
<!DOCTYPE html> <html> <body> <h1>我的第一张网页</h1> <p>我的第一个段落</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 5 + 6; </script> </body> </html>
提示:Pembaruan atribut innerHTML elemen HTML adalah kaedah biasa untuk memaparkan data di HTML.
使用 document.write()
出于测试目的,使用 document.write()
比较方便:
实例
<!DOCTYPE html> <html> <body> <h1>我的第一张网页</h1> <p>我的第一个段落</p> <script> document.write(5 + 6); </script> </body> </html>
注意:在 HTML 文档完全加载后使用 document.write()
将删除所有已有的 HTML :
实例
<!DOCTYPE html> <html> <body> <h1>我的第一张网页</h1> <p>我的第一个段落</p> <button onclick="document.write(5 + 6)">试一试</button> </body> </html>
提示:document.write()
方法仅用于测试。
使用 window.alert()
您能够使用警告框来显示数据:
实例
<!DOCTYPE html> <html> <body> <h1>我的第一张网页</h1> <p>我的第一个段落</p> <script> window.alert(5 + 6); </script> </body> </html>
使用 console.log()
在浏览器中,您可使用 console.log()
方法来显示数据。
请通过 F12 来激活浏览器控制台,并在菜单中选择“控制台”。
实例
<!DOCTYPE html> <html> <body> <h1>我的第一张网页</h1> <p>我的第一个段落</p> <script> console.log(5 + 6); </script> </body> </html>