如果我理解正确的话,您可以使用
tr th, tr td
和
nth-child
选择器来简化它。您可以基于索引进行操作,但需要添加1,因为
nth-child
不像jQuery中的元素那样从0开始索引。而且JS并不需要太详细。我应该提到,在
td:nth
之前放置非常重要,因为你不希望“仅限于每个n个td”。如果是这种情况,则不会在每一行上隐藏所有列。
查看工作jsFIDDLE示例
FYI:如果您想要一个“更清晰”的外观(就像turbotax站点上的外观),则不要隐藏td本身。相反,使其略微宽于您最大的文本段,并将每个文本段放置在每个单元格内的
或div
标记内。然后将您的column
选择器更改为抓取每个单元格的inner元素并隐藏它。
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() {
$("#tableId input[type=checkbox]").on("change", function(e) {
var id = $(this).parent().index()+1,
col = $("table tr th:nth-child("+id+"), table tr td:nth-child("+id+")");
$(this).is(":checked") ? col.show() : col.hide();
}).prop("checked", true).change();
$("button").on("click", function(e) {
$("input[type=checkbox]").prop("checked", true).change();
});
})
td
上使用类。 - SpYk3HH