在网上找了这么多都没有JS生成表格然后JS操作合并单元格的,或者是别人写的太负责了,又不想去理解,所以就自己动手写了个简单点的。

其实代码也不多,思路清晰就基本上可以了。一开始的时候是被colspan蒙了,因为要注意大小写才可以的。看下代码,

 

 
  
  1. <html> 
  2. <head> 
  3. <script type="text/javascript"
  4. function showRowOrColTable(){ 
  5. //创建table
  6.     var table = document.createElement("table"); 
  7.         var projectid=3; //看图下合并多少列就写多少
  8.         table.border = "1"
  9.         var rowIndex = 0; 
  10.         var rowStart = 0; 
  11.         var rowLength = 2; 
  12.         var colIndex = 1; 
  13.         var colLength = 2; 
  14.         var projectLength=projectid*2; 
  15.         for ( var i = 0; i < 5; i++) { 
  16.             var row = table.insertRow(i); 
  17.             for ( var j = 0; j < projectLength+1; j++) { 
  18.                 var cell = row.insertCell(j); 
  19.                 cell.innerHTML = "hello world"; //赋值内容
  20.             } 
  21.         } 
  22.         for ( var j = 0; j <= rowIndex; j++) { 
  23.             table.rows[j].cells[colIndex].colSpan = projectid; 
  24.             table.rows[j].cells[projectid*2-1].colSpan = projectid; 
  25.             for ( var i = 0; i < projectid - 1; i++) { 
  26.                 table.rows[j].deleteCell(colIndex+1); 
  27.                 table.rows[j].deleteCell(3); 
  28.             } 
  29.         } 
  30.         table.rows[rowIndex].cells[rowStart].rowSpan = 2; 
  31.         table.rows[rowIndex + 1].deleteCell(0); 
  32.         table.rows[0].cells[0].innerHTML = "&nbsp;"
  33.         table.rows[0].cells[1].innerHTML = "个人得分"
  34.         table.rows[0].cells[2].innerHTML = "个人准确率"
  35.         table.rows[1].cells[0].innerHTML = "第一"
  36.         table.rows[1].cells[1].innerHTML = "第二"
  37.         table.rows[1].cells[2].innerHTML = "第一"
  38.         table.rows[1].cells[3].innerHTML = "第二"
  39.         var _row=table.rows[1]; 
  40.         document.getElementById("table").appendChild(table); 
  41.     } 
  42.      
  43.     </script> 
  44.     </head> 
  45.     <body onLoad="showRowOrColTable()"
  46.         <div id="table"></div> 
  47.     </body> 
  48.     </html> 

如图: