ブラウザに文字を表示
<htmllang="ja">
<head>
<metacharset="UTF-8">
<title>Hello!</title>
</head>
<body>
<script>
window.document.write('Hellow World!!');
</script>
<noscript>
JavaScript対応ブラウザで表示してください。
</noscript>
</body>
</html>
文字列の表示
JavaScriptで文字列を表示するには、「window.document.write( )」を使います。
window.document.write( )
( )の中の文字列を表示します。「window.」は省略できます。
'(シングルクォーテーション)
表示したい文字列を「 ' 」と「 ' 」ではさみます。
;(セミコロン)
ここまでが1つの文であることを表す記号です。
<htmllang="ja">
<head>
<metacharset="UTF-8">
<title>平成を西暦に変換する</title>
</head>
<body>
<script>
var heisei;
var fullYear;
var message;
heisei = 26;
fullYear = heisei + 1988;
message = '平成' + heisei + '年は' + '西暦' + fullYear + '年です。';
document.write('<h1>', message, '<\/h1>');
</script>
</body>
</html>
標準体重プログラム
<htmllang="ja">
<head>
<metacharset="UTF-8">
<title>標準体重</title>
</head>
<body>
<script>
var height;
var weight;
height = 170;
weight = (height -100) * 0.9;
document.write('<h1>' + '身長が' + height + 'cmの人の標準体重は' + weight, 'kgです。' + '<\/h1>');
</script>
</body>
</html>
警告ダイアログに表示
<htmllang="ja">
<head>
<metacharset="UTF-8">
<title>ありがとう!</title>
</head>
<body>
<script>
window.alert('ありがとう!');
</script>
<noscript>
JavaScript対応ブラウザで表示してください。
</noscript>
</body>
</html>
警告ダイアログ表示
window.alert( )
[OK]ボタンのある警告ダイアログウィンドウに( )の中の文字列を表示します。
「window.」は省略できます。
命令には引数を渡せる
以下は同じ結果になります。
<htmllang="ja">
<head>
<metacharset="UTF-8">
<title>JavaScriptはじめの一歩</title>
</head>
<body>
<script>
document.write('<h1>はじめてのJavaScript</h1>');
document.write('<h1>' , 'はじめてのJavaScript' , '</h1>');
document.write('<h1>' + 'はじめてのJavaScript' + '</h1>');
</script>
<noscript>
JavaScript対応ブラウザで表示してください。
</noscript>
</body>
</html>
変数にまとめてから表示
<htmllang="ja">
<head>
<metacharset="UTF-8">
<title>平成を西暦に変換する</title>
</head>
<body>
<script>
var heisei;
var fullYear;
var message;
heisei = 26;
fullYear = heisei + 1988;
message = '平成' + heisei + '年は' + '西暦' + fullYear + '年です。';
window.alert(message);
</script>
</body>
</html>
メッセージを表示するダイアログボックス