jQueryを読み込む
まずは本家サイトからダウンロードして読み込む。
あるいはGoogleがホスティングするjQueryを読み込む。
Google Hosted Libraries - Developer's Guide
version 1 読み込み例
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
version 2 読み込み例(高機能だが古いIEに非対応など)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
よく使うAPI
実行する
ページロード時に実行する。
$(document).ready(function(){ // ページロード時にこの間のプログラムが実行される。 });
$( function() { // こちらも同じ。 });
クリックしたときに実行する。
$( '#ID' ).click(function() { // IDがクリックされたときにこの間のプログラムが実行される。 });
$(document).on('click','#ID',function(){ // こちらは後から生成された要素(element)にも適用される。 });
取得する
位置を取得する
var position = $(this).position(); var top = position.top; var left = position.left;
変更する
属性を変更する。
$("#id").attr('id', 'my_name')
スタイルや位置を変更する。
$("#id").css({"top":"100px","left":"200px"})
アニメーションでスタイルや位置を変更する。
$("#id").animate({ 'width': "161px", 'height': "240px", 'opacity': '0.0', 'left': '50%', 'top': '50%', 'margin': '-120px 0 0 -80px', },2000);
HTMLを変更する。
$('#id').html(' この内容に差し替える ');
追加する
要素を追加する。
$("#id").appendTo("#element");
要素を先頭に追加する。
$("#id").appendTo("#element");
生成する
要素のクローンを生成する。
$("#id").clone().appendTo("#element");
消去する
要素を消去する。
$('#id').remove();
要素の内容を消去する。
$("#id").empty();
通信する
データを読み込む。(jsonファイルの場合)
$.ajax({ url: 'js/voyager.json', dataType : 'json', success: function( data ) { $( '#id' ).html( data ); }, error: function( data ) { $( '#id' ).html( 'error' ); } });