`

如何用javascript合并表格相同值的行

阅读更多
忘了在哪里看到的一段代码,效率不高,不过如果数据行不是很多的时候还是可以考虑一下的。

//清除空格
String.prototype.Trim = function(){
   return this.replace(/(^\s*)|(\s*$)/g, "");
}

String.prototype.LTrim = function(){
   return this.replace(/(^\s*)/g, "");
}

String.prototype.RTrim = function(){
   return this.replace(/(\s*$)/g, "");
}

/*合并相同值的行
@tbl :要合并的表格对象
@cellIndex:要合并的列
*/
function   MergeCellsVertical(tbl,cellIndex) {
      //如果表格行数少于两行,直接返回
      if (tbl.rows.length < 2) return;  
      var i,j;  
      var last = tbl.rows(0).cells(cellIndex).innerHTML;  
      var lastIndex = 0;      
      for(i = 1; i < tbl.rows.length; i++) {
          //发现新的值
          if(tbl.rows(i).cells(cellIndex).innerHTML != last)  
            {        
              if(i > lastIndex + 1)  
              {  
                  for(j = lastIndex+1; j < i; j++)  
                  {  
                      tbl.rows(j).cells(cellIndex).removeNode();  
                  }  
                  tbl.rows(lastIndex).cells(cellIndex).rowSpan = i-lastIndex;  
              }  
              last = tbl.rows(i).cells(cellIndex).innerHTML;  
              lastIndex = i;  
          }  
      }  
      //最后一行要特别处理  
      if(lastIndex != tbl.rows.length - 1)  
     {        
          for(j = lastIndex + 1; j < tbl.rows.length; j++)  
          {            
              tbl.rows(j).cells(cellIndex).removeNode();  
          }  
          tbl.rows(lastIndex).cells(cellIndex).rowSpan = tbl.rows.length - lastIndex + 1;  
      }  
}  


//页面onload的时候调用这个函数
function loadFinish(){
   var tbl=document.getElementById("tblSearch");
   for(var i=tbl.rows[0].cells.length;i>0;i--){
      var td=tbl.rows[0].cells[i-1].innerText.Trim();
      //合并表格列名为"日期"和"医生姓名"两列
      if(td=='日期'||td=='医生姓名'){
MergeCellsVertical(tblSearch,i-1);
      }
   }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics