欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

合并单元格 博客分类: javascript JavaScripttable单元格合并 

程序员文章站 2024-03-25 16:02:58
...

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>无标题文档 </title> 
</head> 

<body> 
<table width="100%" border="1" cellspacing="0" cellpadding="0" id="tab"> 
  <tr> 
    <td>张三 </td> 
    <td>男 </td> 
    <td>22 </td> 
    <td>数学 </td> 
    <td>90 </td> 
  </tr> 
   <tr> 
    <td>张三 </td> 
    <td>男 </td> 
    <td>22 </td> 
    <td>数学 </td> 
    <td>90 </td> 
  </tr> 
  <tr> 
    <td>张三 </td> 
    <td>男 </td> 
    <td>22 </td> 
    <td>语文 </td> 
    <td>70 </td> 
  </tr> 
  <tr> 
    <td>张三 </td> 
    <td>女 </td> 
    <td>22 </td> 
    <td>英语 </td> 
    <td>60 </td> 
  </tr> 
  <tr> 
    <td>李四 </td> 
    <td>女 </td> 
    <td>22 </td> 
    <td>数学 </td> 
    <td>60 </td> 
  </tr> 
  <tr> 
    <td>李四 </td> 
    <td>女 </td> 
    <td>19 </td> 
    <td>语文 </td> 
    <td>60 </td> 
  </tr> 
  <tr> 
    <td>王五 </td> 
    <td>男 </td> 
    <td>19 </td> 
    <td>英语 </td> 
    <td>60 </td> 
  </tr> 
</table> 

<script type="text/javascript">
window.onload = function(){
    var tab = document.getElementByIdx_x_x("tab");
    var maxCol = 3, val, count, start;  //maxCol:合并单元格作用到多少列    
    for(var col = maxCol-1; col >= 0 ; col--){
        count = 1;
        val = "";
        for(var i=0; i<tab.rows.length; i++){
            if(val == tab.rows[i].cells[col].innerHTML){
                count++;
            }else{
                if(count > 1){ //合并
                    start = i - count;
                    tab.rows[start].cells[col].rowSpan = count;
                    for(var j=start+1; j<i; j++){
                        tab.rows[j].cells[col].style.display = "none";
                    }
                    count = 1;
                }
                val = tab.rows[i].cells[col].innerHTML;
            }
        }
        if(count > 1 ){ //合并,最后几行相同的情况下
            start = i - count;
            tab.rows[start].cells[col].rowSpan = count;
            for(var j=start+1; j<i; j++){
                tab.rows[j].cells[col].style.display = "none";
            }
        }
    }
};
</script>
</body> 
</html>