私があなたの言いたいことを理解したら、セレクターを使用して本当に簡単にすることができtr th, tr td
ますnth-child
。インデックスに基づいて移動できますがnth-child
、jQuery の要素のようにインデックスが 0 ではないため、1 を追加する必要があります。また、JS を引き出す必要はありません。「n番目のtdのみ」を望まないという点で、tr
前に配置することは非常に重要です。td:nth
その場合、すべての行のすべての列を非表示にすることはありません。
参考までに: 「よりクリーンな」外観が必要な場合 (turbotax サイトのように) 、 td自体を非表示にしないでください。代わりに、最大のテキスト部分よりも少し幅を広げ、各テキスト部分を各セル内に配置するp
か、div
タグを各セル内に配置します。次に、column
セレクターを変更して、各セルの内部要素を取得し、代わりに非表示にします。
HTML
<table>
<thead>
<tr>
<th>
<input id="chk1" type="checkbox" />
</th>
<th>
<input id="chk1" type="checkbox" />
</th>
<th>
<input id="chk1" type="checkbox" />
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
col1
</td>
<td>
col2
</td>
<td>
col3
</td>
</tr>
<tr>
<td>
col1
</td>
<td>
col2
</td>
<td>
col3
</td>
</tr>
<tr>
<td>
col1
</td>
<td>
col2
</td>
<td>
col3
</td>
</tr>
<tr>
<td>
col1
</td>
<td>
col2
</td>
<td>
col3
</td>
</tr>
</tbody>
</table>
<button>Reset</button>
JavaScript
$(function() {
// Selects your table by id, then the input checkboxes inside the table, you can
// alternate this call with classnames on your inputs if you're going to have
// more inputs than what's desired in call here.
// also note i'm using the "change" function and not "click", this simply
// provides easier control of what's going on with your inputs and makes
// later calls (like reset) a much easier call. Less thinking required
$("#tableId input[type=checkbox]").on("change", function(e) {
// First variable grabs the inputs PARENT index, this is the TH containing
// the input, thus the column you want hidden.
// The second is calling ALL TH's && TD's having that same index number
var id = $(this).parent().index()+1,
col = $("table tr th:nth-child("+id+"), table tr td:nth-child("+id+")");
// This simple inline "if" statement checks if the input is checked or now
// and shows the columns based on if it IS checked
$(this).is(":checked") ? col.show() : col.hide();
}).prop("checked", true).change(); // here i set all inputs to checked without having to write it in the above HTML
$("button").on("click", function(e) {
$("input[type=checkbox]").prop("checked", true).change();
});
})