トップページ >  Ajax >  jQueryの基本
初版2009/08/11: 最終更新日2009/08/11
jQueryの基本
目次
説明
IDによる選択
ソースサンプル
実行例
タグの種類による選択
サンプルソース
実行例
説明
jQueryの最も基本となるのは、$()関数です。
$()はjQuery()を省略した書き方で、jQuery( ~~ )と書いても$( ~~ )と書いても同じことになりますが、ここでは$()と書きます。
この関数で、HTMLから要素を選択し様々な操作を行います。
IDによる選択
$()の引数として、#idというような引数を与えると、HTMLタグにつけられたid属性により要素を選択します。
下のサンプルでは、id="target_element"の要素の中身をalert()で表示しています。
$( ~~ ).html()と$()に続けて.html()と書いています。 これは選択した要素について、html()を実行するという意味で、html()は要素の中身を表示する関数です。
ソースサンプル
<html>
<head>
<title></title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">google.load("jquery", "1.3");</script>
<script type="text/javascript">
$(document).ready(function(){
function execute_sample(selector){
	if( selector == undefined ){
		selector = '#sample';
	}
	var code = $(selector).html();

	eval(code);
}
</script>
</head>
<body>
	<input type="button" value="サンプル実行" 
	onclick="execute_sample('#sample_id')"><br />
	<span id="sample_id">alert( $("#target_element").html() );</span><br />
</body>
</html>
実行例
以下、実行例です。



alert( $("#target_element").html() );
タグの種類による選択
$()の引数として、タグ名を与えると、そのタグの要素を選択します。
そのタグが複数ある場合には、複数に対して同時に操作することができます。
サンプルでは、spanタグの文字を赤くしています。
その他クラスによる選択( $(".class") )もできます。
サンプルソース
<html>
<head>
<title></title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">google.load("jquery", "1.3");</script>
<script type="text/javascript">
$(document).ready(function(){
function execute_sample(selector){
	if( selector == undefined ){
		selector = '#sample';
	}
	var code = $(selector).html();

	eval(code);
}
</script>
</head>
<body>
	<input type="button" value="サンプル実行" 
	onclick="execute_sample('#sample_tag')"><br />
	<span id="sample_tag">$("span").css('color', 'red');</span>
</body>
</html>
実行例
以下、実行例です。



$("span").css('color', 'red');