js 合并表格

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>
  rowspan();

  function rowspan(){
    var tds = document.querySelectorAll("#test-rowspan td[name='province']"),
        firstTd = null,cn = 1,rowNum = 1,max = tds.length;
    
    Array.from(tds).map(function(item,i){
         var td = item;
         if(i==0){
            firstTd = td;
         }else{
              if(firstTd.innerText.trim()==td.innerText.trim()){
                   cn++;
                   td.previousElementSibling.remove();
                   td.remove();
                   if(max-1-i==0){
                        firstTd.previousElementSibling.setAttribute("rowspan",cn);
                        firstTd.setAttribute("rowspan",cn);
                   }
              }else{
                   if(cn>1){
                        firstTd.previousElementSibling.setAttribute("rowspan",cn);
                        firstTd.setAttribute("rowspan",cn);
                        cn = 1;
                   }
                   firstTd = td;
                   rowNum++;
                   firstTd.previousElementSibling.innerText = 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、效果图

合并前

合并后

posted @ 2016-04-15 09:56  【云】风过无痕  阅读(505)  评论(0编辑  收藏  举报