对@Kishore S. 代码进行了调整,我希望能够对任何列和我想要的任何表进行分组,但要做到这一点,我需要前一列值的哈希值,这样如果你只压缩第 3 列,它不会“桥接”上一列。
所以:
---------------------------------
Value A | Label1 | 1 |
Value A | Label2 | 1 |
Value A | Label3 | 1 |
Value B | Label1 | 1 |
Value B | Label2 | 1 |
Value B | Label3 | 1 |
---------------------------------
将变为(包含第 1 列和第 3 列):
---------------------------------
| Label1 | |
Value A | Label1 | 1 |
| Label1 | |
| Label2 | 1 |
Value B | Label3 | 1 |
| Label4 | 1 |
---------------------------------
代替:
---------------------------------
| Label1 | |
Value A | Label1 | |
| Label1 | 1 |
| Label2 | |
Value B | Label3 | |
| Label4 | |
---------------------------------
无论如何,如果有人需要,这里是调整:
调用:
MergGridCells('MyTableID',[1,3]);
function MergeGridCells(TableID,rCols) {
var dimension_cells = new Array();
var dimension_col = null;
for(Col in rCols) {
dimension_col=rCols[Col];
// first_instance holds the first instance of identical td
var first_Hash="";
var first_instance = null;
var rowspan = 1;
// iterate through rows
$("#"+TableID+"> tbody > tr").children("td").attr('hidden', false);
$("#"+TableID+"> tbody > tr").children("td").attr('rowspan', 1);
$("#"+TableID).find('tr').each(function () {
// find the td of the correct column (determined by the dimension_col set above)
var dimension_td = $(this).find('td:nth-child(' + dimension_col + ')');
var dim_Hash="";
for(x=1;x<dimension_col;x++){
dim_Hash+=$(this).find('td:nth-child(' + x + ')').text();
}
if (first_instance === null) {
// must be the first row
first_instance = dimension_td;
} else if (dimension_td.text() === first_instance.text() && first_Hash === dim_Hash) {
// the current td is identical to the previous AND the Hashes are as well
// remove the current td
// dimension_td.remove();
dimension_td.attr('hidden', true);
++rowspan;
// increment the rowspan attribute of the first instance
first_instance.attr('rowspan', rowspan);
} else {
// this cell is different from the last
first_instance = dimension_td;
first_Hash = dim_Hash;
rowspan = 1;
}
});
}
}
更新 - 所以我的代码运行良好,但 dataTable 的 jQuery 后处理在渲染时仍然会导致问题,因为在浏览页面时行会变得不平衡。第一页总是正确的,其他的就会失败。要解决此问题,需要添加“重置”以在重绘之前取消合并所有内容(请参阅dataTable callback)。因此,下面的示例更新使 dataTable 在绘制后调用您的 Merge 函数(也修复了更改显示长度):
"drawCallback": function( settings ) {
MergeGridCells(TableID,rCols);
},