イベント ハンドラーを割り当てる前に、少し HTML を拡張することを検討してください。
この例のフィドルは次のとおりです。
ここでフィドルの例を参照してください
繰り返し可能な html 構造を反復するには、javascript が必要です。したがって、次のような html 構造があるとします: (フィドルを参照)
<table class="jsSelectAll">
<tbody>
<tr class="select-all">
<td>Select All</td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td>Row Label</td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td>Row Label</td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
</tr>
</tbody>
<tbody>
<tr class="select-all">
<td>Select All</td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td>Row Label</td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
</tr>
</tbody>
</table>
次に、必要に応じてテーブル内の各テーブルと tbody を分割し、行 (必要な場合) と列のポインターをチェックボックスに追加することを検討します。また、次のように、クロージャーを使用してイベントの配線を少し簡単にします。
jQuery(function ($) {
// closures
var $tables = $('table.jsSelectAll');
$tables.each(function () {
// closures
var $table = $(this);
var $tbodies = $table.find('tbody');
$tbodies.each(function () {
// closures
var $tbody = $(this);
var $rows = $tbody.find('tr');
var $selectAllCheckboxes = $tbody.find('.select-all input[type="checkbox"]');
var $allCheckboxes = $tbody.find('tr td input[type="checkbox"]')
// label data cells with rows(if desired) and collumns
$rows.each(function (rowIndex) {
// closures
var $row = $(this);
var $inputs = $row.find('input[type="checkbox"]');
$row.attr('data-row', rowIndex);
$inputs.each(function (colIndex) {
// closures
$cbx = $(this);
$cbx.attr('data-col', colIndex);
});
});
// wire select all for each select-all row checkbox
$selectAllCheckboxes.each(function () {
// closures
var $cbx = $(this)
var fClick = function () {
var iCol = $cbx.attr('data-col');
$allCheckboxes
.filter('[data-col="' + iCol + '"]')
.each(function () {
$(this).prop('checked', true);
});
};
$cbx.click(fClick);
});
});
});
});