jQuery( selector [, context] )
引数
- (string)expression
- 検索式。構文はselectorを参照
- (string|jQuery)context
- 検索対象。省略時は現在のHTMLDOM。
超重要。jQueryの基本となる関数。これを実行するとjQueryオブジェクトが返ってくる。Core以外の関数はjQueryオブジェクトのメソッド。
サンプル
Javascript
// .jqTestにボーダー
$('.jqTest1 .execute').click(function(){
$('.jqTest1 p').css('border', '1px solid #000000');
});
HTML
<div class="jqTest1">
<input type="button" value="ボーダー設定" class="execute" />
<p>jQueryテスト</p>
</div>
contextを指定することで検索範囲を絞ることができる。contextにはjQueryオブジェクト、selectorを渡せる。
サンプル
Javascript
// .jqTest2内からp要素を取得
$('.execute1', '.jqTest2').click(function(){
$('p', $('.jqTest2')).css('backgroundColor', '#CCCCCC');
});
$('.execute2', '.jqTest2').click(function(){
$('p', '.jqTest2 .inner').css('backgroundColor', '#990000');
});
HTML
<div class="jqTest2">
<input type="button" value="jqTest2内のpの背景色変更" class="execute1" />
<input type="button" value="jqTest2 .inner 内のpの背景色変更" class="execute2" />
<p>jQueryテスト outer</p>
<div class="inner">
<p>jQueryテスト inner</p>
</div>
</div>
jQuery( html [, ownerDocument] )
引数
- html
- html
- ownerDocument
- 生成する要素のドキュメント。いまいち不明。
htmlからjQueryオブジェクトを作成する
サンプル
Javascript
$('.jqTest3 .execute').click(function(){
var lis = $('<li>test</li><li>test2</li>');
$('.jqTest3 ul').append(lis);
});
HTML
<div class="jqTest3">
<input type="button" value="LI追加" class="execute" />
<ul>
<li>test3</li>
</ul>
</div>
jQuery( html, props )
引数
- html
- html
- (object)props
- 作成される要素の属性、イベントハンドラが設定できる。
くっそ便利。
サンプル
Javascript
$('.jqTest4 .execute').click(function(){
$('.jqTest4').append($('<button>', {
html: '実行',
class: 'execute2',
click: function(){
alert($(this).text());
}
})).append($('<p>', {
html: '上のボタンを押すと何かおこる',
}).css({
fontWeight: 'bold',
color: 'red'
}));
});
HTML
<div class="jqTest4">
<input type="button" value="ボタン追加" class="execute" />
</div>
IEの場合、input要素の属性変更はできないらしい。
Note: Internet Explorer will not allow you to create an input or button element and change its type; you must specify the type using '<input type="checkbox" />' for example. A demonstration of this can be seen below:
jQuery( html [, ownerDocument] )
jQuery( callback )
引数
- (function)callback
- DOMの構築が完了したときに実行される関数
詳しくはjQuery( callback )
jQueryオブジェクト
jQuery関数を実行して返ってくるjQueryオブジェクトの中身は下記。
サンプル
Javascript
var a = $('p', $('.jqTest5'));
var t = '';
for (var b in a) {
t += '<span class="bold">' + b + "</span> =" + a[b] + "<br /><br />";
}
$('.jqTest5').html(t);
HTML
<div class="jqTest5">
<p>jQuery オブジェクト</p>
</div>