好吧,首先,由于表格是由带有单元格的行构造的,为了选择您需要使用的整列:nth-of-type
所有行上的选择器一起单独选择它们的单元格。
$('table td:nth-of-type(1),table th:nth-of-type(1)');
请注意,我们选择两者<td>
and <th>
也可以选择标题。
现在,如果您只需要隐藏功能,您确实可以向每一列添加一个按钮以用于隐藏目的:
$(function () {
$('table th').each(function () {
$('<button>Hide</button>').appendTo($(this)).click(function () {
var column_index = $(this).parent().index()+1;
$('table td:nth-of-type('+column_index+'),table th:nth-of-type('+column_index+')').hide();
});
});
});
Example 1 http://jsfiddle.net/TheBanana/StLuX/
但是,如果您需要再次显示列,则需要单独放置按钮,否则它们将与列一起消失。
例如,您可以放置一个文本框,在其中指定要隐藏/显示的列的索引,如下所示:
添加到html:
<input id="col_hide" placeholder="insert col index 1+"></input>
<input type="submit" id="bt_hide" value="hide/show" />
js:
$(function () {
$('#bt_hide').click(function () {
var column_index = $('#col_hide').val();
$('table td:nth-of-type(' + column_index + '),table th:nth-of-type(' + column_index + ')').toggle();
});
});
Example 2 http://jsfiddle.net/TheBanana/wp86V/
或者,如果您希望表格更加用户友好,您可以在表格外的每列创建一个按钮:
js:
$(function () {
$('table th').each(function (_id, _value) {
$('<button>Toggle ' + parseInt(_id + 1) + '</button>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(_id + 1) + '),table th:nth-of-type(' + parseInt(_id + 1) + ')').toggle();
e.preventDefault();
});
});
});
Example 3 http://jsfiddle.net/TheBanana/u6P6M/