JSFIDDLEで表示します。
私はこのようなものにHTML5データ属性を使用するのが好きです。次のDOM構造を使用するとdata-target
、トリガーチェックボックスの属性を使用してターゲットチェックボックスを定義できます。ターゲットは有効なjQueryセレクター文字列である必要があります。
HTML:
<input type="checkbox" id="checkUsers" class="checkAll" data-target="input[type=checkbox][rel=users]">
<label for="checkUsers">Users:</label>
<input type="checkbox" rel="users">
<input type="checkbox" rel="users">
<input type="checkbox" rel="users">
<input type="checkbox" rel="users">
<input type="checkbox" rel="users">
<br><br>
<input type="checkbox" id="checkPlaces" class="checkAll" data-target="input[type=checkbox][rel=places]">
<label for="checkPlaces">Places:</label>
<input type="checkbox" rel="places">
<input type="checkbox" rel="places">
<input type="checkbox" rel="places">
<input type="checkbox" rel="places">
<input type="checkbox" rel="places">
次に、トリガーチェックボックスのチェックされた属性に基づいてチェック/チェック解除をトリガーするために定義したターゲットを使用するようにプラグインを設定します。
プラグイン:
(function( $ ){
$.fn.check = function() {
// "this" is a jQuery object of the checkbox that was clicked.
var target = this.data("target");
$(target).attr("checked", this[0].checked);
return this; //maintain chainability
};
})( jQuery );
このメソッドの本当の利点は、イベントをのclass
代わりにアタッチすることで、1つのイベントハンドラー宣言を管理するだけで済むことですid
。
イベントハンドラー宣言:
$(function(){
$(".checkAll").click(function(){
$(this).check();
});
});