js 合并表格

时间:2022-10-13 05:11:47

1、css和js部分

<style type="text/css">
table.altrowstable {
 font-family: verdana,arial,sans-serif;
 font-size:11px;
 color:#333333;
 border-width: 1px;
 border-style: solid;
 border-color: #a9c6c9;
 border-collapse: collapse;
}
table.altrowstable th {
 border-width: 1px;
 padding: 8px;
 border-style: dotted;
 border-color: #a9c6c9;
}
table.altrowstable td {
 border-width: 1px;
 padding: 8px;
 border-style: dotted;
 border-color: #a9c6c9;
}
.oddrowcolor{
 background-color:#d4e3e5;
}
.evenrowcolor{
 background-color:#c3dde0;
}
</style>

<script>

$(function(){

  rowspan();

});

function rowspan(){
    var firstTd = null,cn = 1,rowNum = 1,max = $("#test-rowspan td[name='province']").size();
    var tds = $("#test-rowspan td[name='province']");
    $.each(tds,function(i,item){
     var td = $(item);
     if(i==0){
      firstTd = td;
     }else{
      if(firstTd.text()==td.text()){
       cn++;
       td.prev().remove();
       td.remove();
       if(max-1-i==0){
        firstTd.prev().attr("rowspan",cn);
        firstTd.attr("rowspan",cn);
       }
      }else{
       if(cn>1){
        firstTd.prev().attr("rowspan",cn);
        firstTd.attr("rowspan",cn);
        cn = 1;
       }
       firstTd = td;
       rowNum++;
       firstTd.prev().text(rowNum);
      }
     }
    });
   }

</script>

2、dom表格

<table id="test-rowspan" class="altrowstable" width="200px">
   <tr>
      <td>1</td> <td name="province">上海</td> <td></td>
   </tr>
   <tr>
      <td>2</td> <td name="province">上海</td> <td></td>
   </tr>
   <tr>
      <td>3</td> <td name="province">上海</td> <td></td>
   </tr>
   <tr>
      <td>4</td> <td name="province">广东</td> <td></td>
   </tr>
   <tr>
      <td>5</td> <td name="province">广东</td> <td></td>
   </tr>
   <tr>
      <td>6</td> <td name="province">北京</td> <td></td>
   </tr>
   <tr>
      <td>7</td> <td name="province">天津</td> <td></td>
   </tr>
   <tr>
      <td>8</td> <td name="province">天津</td> <td></td>
   </tr>
   <tr>
      <td>9</td> <td name="province">天津1</td> <td></td>
   </tr>
  </table>

3、效果图

合并前

js 合并表格

合并后

js 合并表格