如何用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);
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值