ダイアログボックスを使った記述
ダイアログボックスを使った記述
3種類のダイアログボックス
項目 | コード |
---|---|
警告 | alert() |
確認 | confirm() |
入力 | prompt() |
メッセージを表示するダイアログボックス
alert( メッセージ );
ユーザーに確認を求めるダイアログボックス
confirm( メッセージ );
変数 = confirm( メッセージ );
- confirmメソッドは「戻り値を返す」
- ブーリアン型「true(真)」または「false(偽)」
ユーザーにデータを入力してもらうダイアログボックス
- promptから取得できた値は「文字列」です
prompt( メッセージ );
変数 = prompt( メッセージ, デフォルトの値 );
警告ダイアログに出力(表示)
- 警告ダイアログに「ありがとう!」と表示させる
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>ありがとう!</title> </head> <body> <script> window.alert( 'ありがとう!' ); </script> <noscript> JavaScript対応ブラウザで表示してください。 </noscript> </body> </html>
警告ダイアログ表示
- JavaScriptで警告ダイアログを表示するには、「window.alert( )」を使います
window.alert( );
- [OK]ボタンのある警告ダイアログウィンドウに( )の中の文字列を表示します
- 「window.」は省略できます。
文字列を出力(表示)
- テンプレートリテラル
- 「バッククォート」で囲む
- 変数は「${変数名}」で文字列内に挿入する
文字列と変数の連結(テンプレートリテラル)
- 「バッククォーテーション」で囲む
- 変数は「${変数}」と記述する
<!DOCTYPE HTML> <html lang="ja"> <head> <meta charset="UTF-8"> <title>平成を西暦に変換する</title> </head> <body> <script> let reiwa; let fullYear; let message; reiwa = 4; fullYear = reiwa + 2018; // message = '令和' + reiwa + '年は、' + '西暦' + fullYear + '年です。'; message = `令和${reiwa}年は、西暦${fullYear}年です。`; window.alert( message ); </script> </body> </html>
ブラウザーで出力(表示)
- document.write( );
- ブラウザーの表示を上書き
parseInt( );
- 文字列を数値に変換
- promptから取得できた「文字列」の値を数値として認識させる関数
- 整数型 【 integer 】 インテジャー
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>標準体重</title> </head> <body> <script> let height; //身長 let weight; //体重 // 身長を入力する height = prompt( '身長を入力してください' ); height = parseInt( height ); // 計算を行う weight = ( height -100 ) * 0.9; // 結果を表示する document.write( `<h1>` ); document.write( `身長が${height}cmの人の標準体重は` ); document.write( `${weight}kgです。` ); document.write( `</h1>` ); </script> </body> </html>