jQueryの読み込み
公式サイトからDL
jQuery: The Write Less, Do More, JavaScript Library
<script type="text/javascript" src="./jquery-1.4.2.min.js"></script>
セレクタによるHTML/CSS操作
HTML部分を変更
$("p#first").html("<strong>変更後</strong>");
<!-- 変更前 --> <p id="first">変更前</p> <!-- 変更後 --> <p id="first"><strong>変更後</strong></p>
挿入
$("p#first").prepend("<strong>要素内先頭</strong>"); $("p#first").append("<strong>要素内最後</strong>"); $("p#first").before("<strong>要素の前</strong>"); $("p#first").after("<strong>要素の後</strong>");
<!-- 変更前 --> <div id="wrap"> <p id="first">変更前</p> </div> <!-- 変更後 --> <div id="wrap"> <strong>要素の前</strong> <p id="first"><strong>要素内先頭</strong>変更前<strong>要素内最後</strong></p> <strong>要素の後</strong> </div>
置き換え
https://gist.github.com/11c1b8d836841eac5519
$("p#first").replaceWith("<div><strong>変更後</strong></div>");
<!-- 変更前 --> <p id="first">変更前</p> <!-- 変更後 --> <div><strong>変更後</strong></div>
フォーム部品の操作
$("input#button").val("変更後");
<!-- ボタンフォーム --> <input type="button" value="変更前" id="button">
イベント設定
ボタンをクリックするとテキストフォームに文字が挿入されるようにします。
// javascript $("input#button").click(function(){ $("input#text").val("ボタンからの挿入"); }); // HTML <input type="text" id="text"> <input type="button" value="挿入" id="button">
下記のようなイベントがあります。
- click (クリック)
- dblclick (ダブルクリック)
- mousedown (マウスダウン)
- mouseup (マウスアップ)
- mouseover (マウスオーバー)
- mouseout (マウスアウト)
- mousemove (マウスムーブ)