文字の表示
JavaScriptには、ブラウザに文字を表示する基本的な操作を実現してくれるdocumentという
オブジェクト と呼ばれるものがあります。
従来のHTMLで
Hello!! You are Welcome
と表示するには、 下の表の左列のように記述していましたが、JavaScriptでは右列のように記述します。
この例では、documentがオブジェクトで、open,writeとcloseがメソッドとなっています。
従来のHTMLによる方法 | JavaScriptによる文字列の表示 |
---|---|
<html> <head> <title>従来のHTML </title> </head> <body> Hello!! You are Welcome </body> </html> |
<html> <head> <script type="text/javascript"> <!-- document.open(); document.write("Hello!! You are Welcome(JavaScript)"); document.close(); //--> </script> </head> <body> </body> </html> |
documentオブジェクトには以下のメソッドがあります。
メソッドのリスト | 用途 | 例 |
---|---|---|
close() | ドキュメントを閉じる | document.close(); |
open() | ドキュメントを開いて書き込み可能にする | document.open(); |
write() | ドキュメントに文字列、数式を表示する | document.write("表示文字"); |
writeln() | 文字列、数式を表示し、最後に改行する。 (実際には改行されない。) | document.writeln("表示文字"); |
<html> <head> </head> <body> <script type="text/javascript"> <!-- document.open(); document.write("<h1>サンプル</h1>"); document.write("<table><tr><td>A</td><td>B</td></tr><tr><td>C</td><td>D</td></tr></table>") document.close(); //--> </script> </body> </html> |
ブラウザでの見え方