jQuery語法
合併上下欄位(colIdx)
jQuery.fn.rowspan = function(colIdx) {
return this.each(function() {
var that;
$('tr', this).each(function(row) {
var thisRow = $('td:eq(' + colIdx + '),th:eq(' + colIdx + ')', this);
if ((that != null) && ($(thisRow).html() == $(that).html())) {
rowspan = $(that).attr("rowSpan");
if (rowspan == undefined) {
$(that).attr("rowSpan", 1);
rowspan = $(that).attr("rowSpan");
}
rowspan = Number(rowspan) + 1;
$(that).attr("rowSpan", rowspan);
$(thisRow).remove(); $(thisRow).hide();
} else {
that = thisRow;
}
that = (that == null) ? thisRow : that;
});
alert('1');
});
}
當指定欄位(colDepend)值相同時,才合併欄位(colIdx)
jQuery.fn.rowspan = function(colIdx, colDepend) {
return this.each(function() {
var that;
var depend;
$('tr', this).each(function(row) {
var thisRow = $('td:eq(' + colIdx + '),th:eq(' + colIdx + ')', this);
var dependCol = $('td:eq(' + colDepend + '),th:eq(' + colDepend + ')', this);
if ((that != null) && (depend != null) && ($(thisRow).html() == $(that).html()) && ($(depend).html() == $(dependCol).html())) {
rowspan = $(that).attr("rowSpan");
if (rowspan == undefined) {
$(that).attr("rowSpan", 1);
rowspan = $(that).attr("rowSpan");
}
rowspan = Number(rowspan) + 1;
$(that).attr("rowSpan", rowspan);
$(thisRow).remove(); $(thisRow).hide();
} else {
that = thisRow;
depend = dependCol;
}
that = (that == null) ? thisRow : that;
depend = (depend == null) ? dependCol : depend;
});
});
}
合併左右欄位
jQuery.fn.colspan = function(rowIdx) {
return this.each(function() {
var that;
$('tr', this).filter(":eq(" + rowIdx + ")").each(function(row) {
$(this).find('th,td').each(function(col) {
if ((that != null) && ($(this).html() == $(that).html())) {
colspan = $(that).attr("colSpan");
if (colspan == undefined) {
$(that).attr("colSpan", 1);
colspan = $(that).attr("colSpan");
}
colspan = Number(colspan) + 1;
$(that).attr("colSpan", colspan);
$(this).remove();
} else {
that = this;
}
that = (that == null) ? this : that;
});
});
});
}
範例一
先來看範例 Html
(一時想不到好的範例,先用文字數字帶過,請大家見諒)
<table id="table1" border="1" class="tbspan">
<tr>
<td>A</td>
<td>B</td>
<td>B</td>
<td>C</td>
<td>C</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
</table>
直接執行的結果
加上合併語法
$(function() {
$('.tbspan').rowspan(0);
$('.tbspan').rowspan(1);
$('.tbspan').colspan(0);
});
合併後執行結果
使用上很簡單吧
範例二
這邊額外說明另一種用法
參考上面的範例,假設我想將第四個欄位上下合併,但是希望根據第一個欄位的值
直接看希望執行的結果,讓大家比較容易理解
預期結果
語法
$(function() {
$('.tbspan').rowspan(3,0);
$('.tbspan').rowspan(0);
$('.tbspan').rowspan(1);
$('.tbspan').colspan(0);
});
說明
這邊利用 $('.tbspan').rowspan(3,0);
其中第一個參數是 合併哪一個欄位
第二個參數是 合併時根據哪個欄位內容要相同,才進行合併