我有大约 30 列和 10 到 500 行之间的 html 表格。我想通过单击按钮来显示/隐藏一组列。
我尝试了两种方法
- 迭代表的标题并在 TH 和 TD 上执行 .show() 或 .hide()。
- 迭代表的标题并更改类以显示/隐藏 TH 和 TD。
该函数的实现如下代码片段。然而,性能并不是那么出色。显示/隐藏 20 列大约需要 5~10 秒,大约 80~120 行数据。
我只是想知道我们是否可以做些什么来让它运行得更快。
function ToggleHeadVisibility(showHide) {
var index = 0;
$('#' + gridViewName + ' thead th').each(function(index) {
index++;
if (showHide == "SHOW") {
/*
$('#' + gridViewName + ' th:nth-child(' + (index) + ')').show();
$('#' + gridViewName + ' td:nth-child(' + (index) + ')').show();
*/
$('#' + gridViewName + ' th:nth-child(' + (index) + ')').removeClass('columnHide');
$('#' + gridViewName + ' td:nth-child(' + (index) + ')').removeClass('columnHide');
} else if (showHide = "HIDE") {
/*
//if (showColumnArray.has($(this).get(0).innerHTML)) {
if (showColumnArray.has($(this).attr('title'))) {
$('#' + gridViewName + ' th:nth-child(' + (index) + ')').show();
$('#' + gridViewName + ' td:nth-child(' + (index) + ')').show();
}
else {
$('#' + gridViewName + ' th:nth-child(' + (index) + ')').hide();
$('#' + gridViewName + ' td:nth-child(' + (index) + ')').hide();
}
*/
if (showColumnArray.has($(this).attr('title'))) {
$('#' + gridViewName + ' th:nth-child(' + (index) + ')').removeClass('columnHide');
$('#' + gridViewName + ' td:nth-child(' + (index) + ')').removeClass('columnHide');
} else {
$('#' + gridViewName + ' th:nth-child(' + (index) + ')').addClass('columnHide');
$('#' + gridViewName + ' td:nth-child(' + (index) + ')').addClass('columnHide');
}
}
});
}
最佳答案
一些建议:
在构建表格时,将
col1、col2、col3
等 css 类添加到标题和数据单元格。然后您只需执行$("td.col1").hide();
即可隐藏相应的列。它比第 n 个子选择器更快。在 IE 和 Firefox 中,您可以将
visibility:collapse
设置为col
元素来折叠整个列。这会快得多。不幸的是,Webkit 浏览器不支持 http://www.quirksmode.org/css/columns.html 。您可以根据浏览器对代码进行分支,以便至少在 IE 和 Firefox 中速度更快。如果您的表格具有
table-layout:fixed
,则可能会显着提高性能,因为您的浏览器不必在每次触摸表格时都不断计算列的宽度,如下所示在自动模式下。考虑从 DOM 树中删除表(通过
.remove()
),执行批量显示/隐藏操作并将其插入回。无论何时,只要您想要,这都是一般规则对 DOM 树进行批量操作。
关于jQuery 在大表性能上显示/隐藏列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3143268/