2007-09-14

初めてのJavaScript - HTMLファイル

<html><head&gt;<title>Hello JavaScript World!</title><style type="text/css">
<!--
  .select {
    margin-left: 30px;
    padding: 0 2px;
    width: 6em;
    border: dotted 1px;
  }
  .select p {
    margin: 2px;
  }
-->
</style></head&gt;<body><script type="text/javascript">
<!--
  // step 1 : output text
  document.write("Hello world!");

  // step 2 : output html
  document.write("<br/><b>Hello javascript world!</b>");

  // step 3 : manipulate DOM
  var p1 = document.createElement("p");
  p1.appendChild(document.createTextNode("Hello DOM world!"));
  document.body.appendChild(p1);

  // step 3 : interactive, using function, event handler
  function solid() {
    this.style.borderStyle="solid";
  }
  var p2 = document.createElement("p");
  p2.appendChild(document.createTextNode("Hello interactive world!"));
  document.body.appendChild(p2);
  p2.addEventListener("click", solid, false); // not solid()

  // step 4 : using object, prototype, closure
  function P(str) {
    this.str = str;
  }
  P.prototype.regist = function(parent){
    this.elem = document.createElement("p");
    this.elem.appendChild(document.createTextNode(this.str));
    parent.appendChild(this.elem);
    var self = this;
    this.elem.addEventListener("click", function(){self.act()}, false);
    // otherwise
    //  this.elem.helloworld = this;
    //  this.elem.addEventListener("click", function(){this.helloworld.act()}, false);
    // bad way
    //  this.elem.addEventListener("click", this.act, false);
    //  this.elem.addEventListener("click", function(){this.act()}, false);
  };
  P.prototype.act = function(){};

  var p3 = new P("Hello prototype world!");
  p3.act = function(){
    if (this.elem.style.borderStyle == ""){
      this.elem.style.borderStyle = "solid";
    } else {
      this.elem.style.borderStyle = "";
    }
  };
  p3.regist(document.body);

  // step 5 : inheritance
  function SELECT(parent, str) {
    this.str = str;
    this.regist(parent);
  }
  SELECT.prototype = new P();
  SELECT.prototype.act = function(){
    p4.elem.style.borderStyle = this.str;
    p4.div.style.display = "none";
  }

  var p4 = new P("Hello world!");
  p4.div = document.createElement("div");
  p4.div.className = "select";
  p4.div.style.display = "none";
  p4.select = [
    new SELECT(p4.div, "none"),
    new SELECT(p4.div, "dotted"),
    new SELECT(p4.div, "solid")
  ];
  p4.act = function(){
    p4.div.style.display = "block";
  };
  p4.regist(document.body);
  document.body.appendChild(p4.div);

//-->
</script></body></html>

記事への反応(ブックマークコメント)

ログイン ユーザー登録
ようこそ ゲスト さん