今更だけど JavaScript 勉強を始めるよ!

ベースになる HTML ファイルの準備

まずはベースにする HTML ファイルを作る.
とりあえず内容は↓

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="ja">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta http-equiv="content-style-type" content="text/css">
    <meta http-equiv="content-script-type" content="javascript">
    <title>タイトル</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script type="text/javascript" src="./main.js"></script>
  </head>
  <body>
  </body>
</html>


この 1 行を追加しておいて外部ファイルを使えるようにしておく.

    <script type="text/javascript" src="./main.js"></script>

Hello, World!

main.js を編集して Hello, World! を作ろー

alert で Hello, World!

alert 関数をつかってみる.

alert("Hello, World!");

こんなダイアログが表示された!!

f:id:kei10in:20100509224312p:image

document.write を使ってみる

document.write っていうのを使ってみる.

document.write("Hello, World!");

こんな風に表示された.

f:id:kei10in:20100509225025p:image

どこに write されるのか試す
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="ja">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta http-equiv="content-style-type" content="text/css">
    <meta http-equiv="content-script-type" content="javascript">
    <title>Test JavaScript</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script type="text/javascript">
      <!--
         document.write("Hello, World!");
         // -->
    </script>
  </head>
  <body>
    <h1>foobar</h1>
  </body>
</html>

f:id:kei10in:20100509225026p:image

タグを追加してみる.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="ja">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta http-equiv="content-style-type" content="text/css">
    <meta http-equiv="content-script-type" content="javascript">
    <title>Test JavaScript</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script type="text/javascript">
      <!--
         document.write("<h1>Hello, World!</h1>");
         // -->
    </script>
  </head>
  <body>
    <h1>foobar</h1>
  </body>
</html>

f:id:kei10in:20100509230156p:image

Event Listener を使って Hello, World!
window.addEventListener("load", function () {
                              elem = document.createElement("p");
                              elem.textContent = "Hello, World!";
                              document.body.appendChild(elem);
                          }, false);

f:id:kei10in:20100510005314p:image

まとめ

今日は 3 種類の Hello, World! を作ってみました.

おなかが空いた & 眠いので今日は寝ます.