如果我明白你的意思,你可以使用tr th, tr td
和nth-child
选择器让它变得非常简单。您可以基于索引,但您需要添加 1,因为nth-child
不是 0 索引,就像 jQuery 中的元素一样。并且 JS 并不真的必须被抽出。我应该提到,放在tr
前面td:nth
非常重要,因为你不想要“只有第 n 个 td”。如果是这样的话,你不会隐藏每一行的每一列。
仅供参考:如果您想要看起来“更干净”的东西(例如在 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();
});
})