DIV CSS 佈局教程網

用 jQuery 自動合併表格中相鄰的相同文本單元格
編輯:JQuery特效代碼     

需求背景

已經生成的數據表格大致內容如下(部分列省略):

地區 / 地區 / 商品代碼 / 商品名稱 ……

廣東 深圳 00028 紅花油
廣東 深圳 00028 紅花油
廣東 深圳 00028 紅花油
廣東 廣州 00027 白花油
廣東 廣州 00028 紅花油
廣東 深圳 00028 紅花油 ……

我們希望把前幾列中「文本相同的相鄰單元格」自動合併,合併後的效果是:相同內容的連續單元格被整合成一格,通過 rowspan 或 colspan 縱向或橫向跨越。

實現步驟

1、在 html 的 head 中引入 jQuery。

2、添加合併單元格的函數:

//函數說明:合併指定表格(表格 id 為 _w_table_id)指定列(列數為 _w_table_colnum)的相同文本的相鄰單元格
//參數說明:_w_table_id 為需要進行合併單元格的表格的 id。如在 HTML 中指定表格 id="data",此參數應為 #data
//參數說明:_w_table_colnum 為需要合併單元格的所在列。為數字,從最左邊第一列為 1 開始算起。
function _w_table_rowspan(_w_table_id,_w_table_colnum){
_w_table_firsttd = "";
_w_table_currenttd = "";
_w_table_SpanNum = 0;
_w_table_Obj = $(_w_table_id + " tr td:nth-child(" + _w_table_colnum + ")");
_w_table_Obj.each(function(i){
if(i==0){
_w_table_firsttd = $(this);
_w_table_SpanNum = 1;
}else{
_w_table_currenttd = $(this);
if(_w_table_firsttd.text()==_w_table_currenttd.text()){
_w_table_SpanNum++;
_w_table_currenttd.hide(); //remove();
_w_table_firsttd.attr("rowSpan",_w_table_SpanNum);
}else{
_w_table_firsttd = $(this);
_w_table_SpanNum = 1;
}
}
});
}

//函數說明:合併指定表格(表格 id 為 _w_table_id)指定行(行數為 _w_table_rownum)的相同文本的相鄰單元格
//參數說明:_w_table_id 為需要進行合併單元格的表格 id。如在 HTML 中指定表格 id="data",此參數應為 #data
//參數說明:_w_table_rownum 為需要合併單元格的所在行。其參數形式請參考 jQuery 中 nth-child 的參數。
// 如果為數字,則從最左邊第一行為 1 開始算起。
// "even" 表示偶數行;"odd" 表示奇數行;"3n+1" 表示行數為 1、4、7、10……
//參數說明:_w_table_maxcolnum 為指定行中單元格對應的最大列數,列數大於這個數值的單元格將不進行比較合併。
// 此參數可以為空,為空則指定行的所有單元格都要進行比較合併。
function _w_table_colspan(_w_table_id,_w_table_rownum,_w_table_maxcolnum){
if(_w_table_maxcolnum == void 0){_w_table_maxcolnum=0;}
_w_table_firsttd = "";
_w_table_currenttd = "";
_w_table_SpanNum = 0;
$(_w_table_id + " tr:nth-child(" + _w_table_rownum + ")").each(function(i){
_w_table_Obj = $(this).children();
_w_table_Obj.each(function(i){
if(i==0){
_w_table_firsttd = $(this);
_w_table_SpanNum = 1;
}else if((_w_table_maxcolnum>0)&&(i>_w_table_maxcolnum)){
return "";
}else{
_w_table_currenttd = $(this);
if(_w_table_firsttd.text()==_w_table_currenttd.text()){
_w_table_SpanNum++;
_w_table_currenttd.hide(); //remove();
_w_table_firsttd.attr("colSpan",_w_table_SpanNum);
}else{
_w_table_firsttd = $(this);
_w_table_SpanNum = 1;
}
}
});
});
}

3、在 html 的 head 中調用合併函數:

<script type="text/javascript"><!--
$(document).ready(function(){
_w_table_rowspan("#spdata",4);
_w_table_rowspan("#spdata",3);
_w_table_rowspan("#spdata",2);
_w_table_rowspan("#spdata",1);
});
// -->
</script>

核心思路很簡單:_w_table_rowspan 按列遍歷,把連續相同文本的單元格隱藏並累加 rowSpan;_w_table_colspan 則按行遍歷,用同樣的比較方式累加 colSpan。注意調用時應從右向左逐列合併,以免前面列的合併影響後面列的行對齊。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved