LoginSignup
2
5

More than 5 years have passed since last update.

【初心者向け】JavaScript入門①「alert / document.write」 |『文系の人にもわかるプログラミング入門』より

Posted at

はじめに

初めてのJavaScript(サイ本)を買いましたが、筆者にとって少しとっつきにくかったです。そこで、本書のサポートページで紹介されていた初心者向けのコラム『JavaScriptで学ぶ文系の人にもわかるプログラミング入門』から学ぶことにしました。

本記事は、その学習記録です。

学習すること

第3章 JavaScriptの第一歩

  • ①ダイアログボックスの表示(alert)
  • ②HTMLとして書く(document.write)
  • ③イベント稼動型のスクリプト
    • ③-①ページを開いたとき実行(onload)
    • ③-②対象をクリックしたとき実行(onclick)

①ダイアログボックスの表示(alert)

example03-01.html(初めてのJavaScriptプログラム)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello</title>
</head>
<body>
<script type="text/javascript">  //JavaScriptのプログラムは<script>タグで囲まれる
alert("Hello!");  // 引数に指定した文字列をダイアログ画面に表示
</script>
<p>ごあいさつでした。</p>
</body>
</html>

②HTMLとして書くーdocument.write()

example03-02.html(document.writeを使う)

<script type="text/javascript">
document.write("<h1>Hi!</h1>");   //引数に指定した文字列をHTMLとして表示
</script>

③イベント稼動型のスクリプトー何かが起こったときに実行される

③-① ページを開いたとき動作(onload)

example03-03.html(イベント稼動型のスクリプト)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello</title>
<script type="text/javascript">
function sayHello(){
    alert("Hi!"); //ダイアログボックスを表示
}
</script>
</head>

<body onload="sayHello();">
<p>ごあいさつです。</p>
</body>
</html>

③-② 対象をクリック時に実行(onclick)

example03-04.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello</title>
</head>
<body>
<p onclick="sayHello()">この文字をクリック(タップ)すると...</p>

<script type="text/javascript">
function sayHello(){
    alert("Hi!"); // ダイアログボックスを表示
}
</script>

</body>
</html>

まとめ

HTML

  • <script>...</script>ーーJavaScriptのスクリプト(プログラム)を囲むHTMLタグ
  • <body onload="関数名()">ー(サイトを開くとき)
  • <xx onclick="関数名()">ー(クリックやタップが行われたとき)

JavaScriptの関数

  • alert()ーダイアログボックスを表示する
  • document.write()ーHTMLのコードをJavaScriptから出力する
2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5