jQueryのいろは

目次

jQueryの特徴

jQueryの特徴
スタイルと規約
  • チェイン(連鎖)
    • $("div").hide().text("new content").addClass("updatedContent").show();
    • 同一要素を複数回選択するより処理効率も高い
  • 選択セットを変数に格納する際には、その変数の先頭に$をつけて、その変数がjQueryオブジェクトであることを示す
    • $divs=$("div");
jQueryオブジェクト(ラッパー)
  • 0〜N個のDOM要素を含む(配列で格納)
    • セレクタで選択されるDOM要素が存在しない場合もnullにならない
  • DOM配列は$().get()、DOM要素は$()[0]で取得する
  • DOM要素からjQueryオブジェクトを取得する場合は$(element)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="blackbird/blackbird.js"></script>
    <link type="text/css" rel="Stylesheet" href="blackbird/blackbird.css" />
    <script type="text/javascript">
      $(function() {
        log.debug(document.getElementById("div1") === document.getElementById("div1"));  //true
        log.debug(document.getElementById("div1") === $("#div1"));  //false
        log.debug(document.getElementById("div1") === $("#div1")[0]); //true
        log.debug($("#div1").length);  //1
        log.debug($("div").length);  //2
        log.debug(document.getElementById("div3") === null);  //true
        log.debug($("div3") === null);  //false
        log.debug($("div3").length);  //0
      });
    </script>
  </head>
  <body>
    <div id="div1">div1</div>
    <div id="div2">div2</div>
  </body>
</html>

よく使う要素選択

基本的なセレクタ
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="blackbird/blackbird.js"></script>
    <link type="text/css" rel="Stylesheet" href="blackbird/blackbird.css" />
    <script type="text/javascript">
      $(function() {
        log.debug($("div").length);  //2 要素セレクタ
        log.debug($("#div1").html());  //div1 idセレクタ
        log.debug($(".class1").length);  //2 classセレクタ
        log.debug($(".class1 strong").html());  //strong1 子孫セレクタ(特定の要素の内側にある要素をさらに絞り込む)
        log.debug($("#array\\[0\\]\\.url").html());  //http://www.google.com エスケープが必要!
      });
    </script>
  </head>
  <body>
    <div id="div1">div1</div>
    <div id="div2">
      <ul id="ul1">
	<li id="first" class="class1">li <strong>strong1</strong> 1-1</li>
	<li id="second" class="class1"></li>
	<li id="third" class="class2">li <strong>strong2</strong> 1-3</li>
	<li id="fourth" class="class2">li 1-4</li>
      </ul>
      <span id="array[0].url">http://www.google.com</span>
    </div>
  </body>
</html>
  • idは要素をユニークに識別するもの。複数の要素を識別したい場合はclassを用いる。
  • メタ文字は”\\”でエスケープが必要
    • !"#$%&'()*+,./:;<=>?@[\]^`{|}~
属性セレクタ
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="blackbird/blackbird.js"></script>
    <link type="text/css" rel="Stylesheet" href="blackbird/blackbird.css" />
    <script type="text/javascript">
      $(function() {
        log.debug($("input[type='checkbox']").length); //3
        log.debug($("[title]").length); //2 特定の属性を持つ要素
        log.debug($("[title='title1']").html()); //li1
        log.debug($("li[title!='title1']").html()); //li2
        log.debug($("input[name='array[0].url']").val()); //http://www.google.com
      });
    </script>
  </head>
  <body>
    <form>
      <div>
	<input type="checkbox" id="checkbox1" value="check1"/>check1
	<input type="checkbox" id="checkbox2" value="check2" checked="checked"/>check2
	<input type="checkbox" id="checkbox3" value="check3"/>check3
      </div>
      <div>
	<input type="text" name="array[0].url" value="http://www.google.com" />
      </div>
    </form>
    <ul>
      <li title="title1">li1</li>
      <li title="title2">li2</li>
    </ul>
  </body>
</html>
  • 属性名の前に”@”をつける必要があったのは、jQuery1.2まで。
フィルタ
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="blackbird/blackbird.js"></script>
    <link type="text/css" rel="Stylesheet" href="blackbird/blackbird.css" />
    <script type="text/javascript">
      $(function() {
        log.debug($("li:first").html());  //li0 text
        log.debug($("li:last").html());  //li6 text
        log.debug($("li:even").length);  //4(偶数番目)
        log.debug($("li:odd").length);  //3(奇数番目)
        log.debug($("li:eq(4)").html());  //li4 text
        log.debug($("li:gt(4)").length);  //2
        log.debug($("li:lt(4)").length);  //4
      });
    </script>
  </head>
  <body>
    <ul id="ul1">
      <li id="li0">li0 text</li>
      <li id="li1">li1 text</li>
      <li id="li2">li2 text</li>
      <li id="li3">li3 text</li>
      <li id="li4">li4 text</li>
      <li id="li5">li5 text</li>
      <li id="li6">li6 text</li>
    </ul>
  </body>
</html>
トラバース
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="blackbird/blackbird.js"></script>
    <link type="text/css" rel="Stylesheet" href="blackbird/blackbird.css" />
    <script type="text/javascript">
      $(function() {
        log.debug($("li:first").text());  //li1 link strong
        log.debug($("li:first").html());  //li1 <a href="#">link</a> <strong>strong</strong>
        $("li:first").html("original");  //HTMLの変更
        $("li:first").prepend("<strong>先頭に挿入</strong>");
        $("li:first").append("<strong>最後に挿入</strong>");
        log.debug($("li:first").html());  //<strong>先頭に挿入</strong>original<strong>先頭に挿入</strong>
        $("li:eq(1)").prependTo("#ul1");  //ul1内部の最初に移動
        $("#li2").clone(true).appendTo("#ul1");  //ul1内部の最後に移動
        $(document.createElement("p")).attr("id", "p1").html("p1").insertAfter("#ul1");  //ul1の次に追加
      });
    </script>
  </head>
  <body>
    <div>
      <ul id="ul1">
	<li id="li1">li1 <a href="#">link</a> <strong>strong</strong></li>
	<li id="li2">li2</li>
      </ul>
    </div>
  </body>
</html>
チェックボックスラジオボタン
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="blackbird/blackbird.js"></script>
    <link type="text/css" rel="Stylesheet" href="blackbird/blackbird.css" />
    <script type="text/javascript">
      $(function() {
        log.debug($("input:checkbox:checked").length);  //2
        log.debug($("input[type='checkbox']").filter(":checked").length);  //2 こっちのがパフォーマンスは良いらしい
        log.debug($("input[type='radio']").filter(":checked").val());  //v1
      });
    </script>
  </head>
  <body>
    <form>
      <div>
	<input type="checkbox" name="checkbox" id="c0" value="v0" /><label for="c0">0</label>
	<input type="checkbox" name="checkbox" id="c1" value="v1" checked="checked" /><label for="c1">1</label>
	<input type="checkbox" name="checkbox" id="c2" value="v2" /><label for="c2">2</label>
	<input type="checkbox" name="checkbox" id="c3" value="v3" checked="checked" /><label for="c3">3</label>
	<input type="checkbox" name="checkbox" id="c4" value="v4" /><label for="c4">4</label>
      </div>
      <div>
	<input type="radio" name="radio" id="r0" value="v0" /><label for="r0">0</label>
	<input type="radio" name="radio" id="r1" value="v1" checked="checked" /><label for="r1">1</label>
	<input type="radio" name="radio" id="r2" value="v2" /><label for="r2">2</label>
      </div>
    </form>
  </body>
</html>

よく使うメソッド

ready()
  • $(document).ready(function(){});
    • 省略表記(推奨):$(function(){});
  • DOM構築時点で呼ばれるため、画像の読み込み完了時点で起こるwindow.onloadイベントより先
    • 複数定義した場合は、定義した順に実行される(上書きされない)
ループ($().each())
  • $().each(function(i, e){});
    • i:現在のインデックス
    • e:現在のDOMオブジェクト(jQueryオブジェクトでない!)
    • function内での”this”は”e”と同一(DOMオブジェクト)、jQueryオブジェクトは$(this)で取得する
  • continue/breakはreturn true/return falseで代替
  • jQuery().each(object, callback)とは別物
    • こちらはjQueryオブジェクト以外の配列等も処理可能なユーティリティメソッド
  • 要素を絞りこんでからループを回すと可読性が高い
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="blackbird/blackbird.js"></script>
    <link type="text/css" rel="Stylesheet" href="blackbird/blackbird.css" />
    <script type="text/javascript">
      $(function() {
        $("div.class1").each(function(i, e) {
          if (i == 1) return true;  //continue
          if (i == 3) return false;  //break
          log.debug(i);
          log.debug(e === this);
          log.debug($(this).html());
        });
      });
    </script>
  </head>
  <body>
    <div id="div1">div1</div>
    <div id="div2" class="class1">div2</div>
    <div id="div3">div3</div>
    <div id="div4" class="class1">div4</div>
    <div id="div5" class="class1">div5</div>
    <div id="div6">div6</div>
    <div id="div7" class="class1">div7</div>
  </body>
</html>


HTML操作
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="blackbird/blackbird.js"></script>
    <link type="text/css" rel="Stylesheet" href="blackbird/blackbird.css" />
    <script type="text/javascript">
      $(function() {
        log.debug($("li:first").text());  //li1 link strong
        log.debug($("li:first").html());  //li1 <a href="#">link</a> <strong>strong</strong>
        $("li:first").html("original");  //HTMLの変更
        $("li:first").prepend("<strong>先頭に挿入</strong>");
        $("li:first").append("<strong>最後に挿入</strong>");
        log.debug($("li:first").html());  //<strong>先頭に挿入</strong>original<strong>先頭に挿入</strong>
        $("li:eq(1)").prependTo("#ul1");  //ul1内部の最初に移動
        $("#li2").clone(true).appendTo("#ul1");  //ul1内部の最後に移動
        $(document.createElement("p")).attr("id", "p1").html("p1").insertAfter("#ul1");  //ul1の次に追加
      });
    </script>
  </head>
  <body>
    <div>
      <ul id="ul1">
	<li id="li1">li1 <a href="#">link</a> <strong>strong</strong></li>
	<li id="li2">li2</li>
      </ul>
    </div>
  </body>
</html>
CSS操作
  • 複数のCSS属性を同時に設定する場合、プロパティ名をキャメルケースで記述すれことでダブルクォーテーションで括らなくても設定可能
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
      $(function() {
        $("#p1").css("background-color", "pink");
        $("#p1").css({
          color : "blue",
          fontWeight : "bold"
        });
        $("#p2").css({
          "background-color" : "yellow",
          "font-weight" : "bold"
        });
      });
    </script>
  </head>
  <body>
    <div>
      <p id="p1">test1</p>
      <p id="p2">test2</p>
    </div>
  </body>
</html>
イベント追加
  • $().trigger(“イベント”)でイベントを起こすことができる
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
      $(function() {
        $("li").click(function(){
          alert($(this).index("#ul1 li"));  //要素内でのインデックスを取得
        }).mouseover(function(){
          $(this).css("background-color", "yellow");
        }).mouseout(function(){
          $(this).css("background-color", "");
        });
        $("#li4").trigger("click");  //イベントを発生させる
      });
    </script>
  </head>
  <body>
    <ul id="ul1">
      <li id="li0">li0 text</li>
      <li id="li1">li1 text</li>
      <li id="li2">li2 text</li>
      <li id="li3">li3 text</li>
      <li id="li4">li4 text</li>
      <li id="li5">li5 text</li>
      <li id="li6">li6 text</li>
    </ul>
  </body>
</html>

実装例

要素が見えるようにスクロールする
  • jQueryレシピブック』 p.145を参考に作成
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
      $(function() {
        for(var i=0; i<100; i++) {
	  $(document.createElement("li")).html("text" + i).appendTo("#ul1");
        }
        var $div = $("#div1");
	var divOffset = $div.offset().top;
	var destination = $div.scrollTop() - divOffset + $("#div1 li:eq(50)").offset().top;
	$div.animate({scrollTop: destination}, 3000);
        $("#button1").click(function(){
          $div.scrollTop($div.scrollTop() - divOffset + $("#div1 li:eq(80)").offset().top);
	});
      });
    </script>
  </head>
  <body>
    <input type="button" id="button1" value="click!!" />
    <div id="div1" style="height:200px; width:200px; overflow:auto; posisiton:relative;">
      <ul id="ul1">
      </ul>
    </div>
  </body>
</html>


チェックボックスの全選択
  • jQueryレシピブック』 p.226を参考に作成
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
      var toggleCheckbox = function(toggleId, checkboxesClass) {
        var $toggle = $("#" + toggleId);
        var $checkboxes = $("input:checkbox." + checkboxesClass);
        $toggle.click(function(){
          if (this.checked) {
            $checkboxes.attr("checked", "checked");
          } else {
            $checkboxes.removeAttr("checked");
          }
        });
        $checkboxes.click(function(){
          if (this.checked) {
            if($checkboxes.length == $checkboxes.filter(":checked").length){
              // 当該チェックボックスがオンで、すべてのチェックボックスがオンの場合
              $toggle.attr("checked", "checked");
            }
          } else {
            $toggle.removeAttr("checked");
          }
        });
      };
      
      $(function() {
        toggleCheckbox("toggle1", "checkbox1");
        toggleCheckbox("toggle2", "checkbox2");
      });
    </script>
  </head>
  <body>
    <form>
      <div>
        <input type="checkbox" id="toggle1" /><label for="toggle1">Select All</label>
        <input type="checkbox" name="checkbox1" class="checkbox1" value="1" id="1-1" /><label for="1-1">1</label>
        <input type="checkbox" name="checkbox1" class="checkbox1" value="2" id="1-2" /><label for="1-2">2</label>
        <input type="checkbox" name="checkbox1" class="checkbox1" value="3" id="1-3" /><label for="1-3">3</label>
      </div>
      <div>
        <input type="checkbox" id="toggle2" /><label for="toggle2">Select All</label>
        <input type="checkbox" name="checkbox2" class="checkbox2" value="1" id="2-1" /><label for="2-1">A</label>
        <input type="checkbox" name="checkbox2" class="checkbox2" value="2" id="2-2" /><label for="2-2">B</label>
        <input type="checkbox" name="checkbox2" class="checkbox2" value="3" id="2-3" /><label for="2-3">C</label>
      </div>
    </form>
  </body>
</html>

参考

  • 『Web制作の現場で使う jQueryデザイン入門』
    • お勧め!

Web制作の現場で使う jQueryデザイン入門 (WEB PROFESSIONAL)

Web制作の現場で使う jQueryデザイン入門 (WEB PROFESSIONAL)

  • jQueryクックブック』

jQueryクックブック

jQueryクックブック