我写了一个关于如何使用 jquery 对任何表进行行跨度的示例。
请注意,代码仅在 1 个假设下有效:您希望行跨度的列已排序
您可以在 Codepen 上使用它 (尝试编辑 indexOfColumnToRowSpan)
JS:
$(function(){
//assumption: the column that you wish to rowspan is sorted.
//this is where you put in your settings
var indexOfColumnToRowSpan = 0;
var $table = $('#myTable');
//this is the code to do spanning, should work for any table
var rowSpanMap = {};
$table.find('tr').each(function(){
var valueOfTheSpannableCell = $($(this).children('td')[indexOfColumnToRowSpan]).text();
$($(this).children('td')[indexOfColumnToRowSpan]).attr('data-original-value', valueOfTheSpannableCell);
rowSpanMap[valueOfTheSpannableCell] = true;
});
for(var rowGroup in rowSpanMap){
var $cellsToSpan = $('td[data-original-value="'+rowGroup+'"]');
var numberOfRowsToSpan = $cellsToSpan.length;
$cellsToSpan.each(function(index){
if(index==0){
$(this).attr('rowspan', numberOfRowsToSpan);
}else{
$(this).hide();
}
});
}
})();
html:
<table id="myTable">
<tbody>
<tr>
<th align="left">A</th>
<th align="left">B</th>
<th align="left">C</th>
<th align="left">D</th>
</tr>
<tr>
<td>Apple</td>
<td>x</td>
<td>y</td>
<td>z</td>
</tr>
<tr>
<td>Apple</td>
<td>x</td>
<td>y</td>
<td>z</td>
</tr>
<tr>
<td>Apple</td>
<td>x</td>
<td>y</td>
<td>z</td>
</tr>
<tr>
<td>Apple</td>
<td>x</td>
<td>y</td>
<td>z</td>
</tr>
<tr>
<td>Apple</td>
<td>x</td>
<td>y</td>
<td>z</td>
</tr>
<tr>
<td>Pear</td>
<td>x</td>
<td>y</td>
<td>z</td>
</tr>
<tr>
<td>Pear</td>
<td>x</td>
<td>y</td>
<td>z</td>
</tr>
<tr>
<td>Pear</td>
<td>x</td>
<td>y</td>
<td>z</td>
</tr>
<tr>
<td>Orange</td>
<td>x</td>
<td>y</td>
<td>z</td>
</tr>
<tr>
<td>Orange</td>
<td>x</td>
<td>y</td>
<td>z</td>
</tr>
<tr>
<td>Orange</td>
<td>x</td>
<td>y</td>
<td>z</td>
</tr>
<tr>
<td>Orange</td>
<td>x</td>
<td>y</td>
<td>z</td>
</tr>
<tr>
<td>Orange</td>
<td>x</td>
<td>y</td>
<td>z</td>
</tr>
<tr>
<td>Orange</td>
<td>x</td>
<td>y</td>
<td>z</td>
</tr>
</tbody>
</table>