在網上找了這麼多都沒有JS產生表格然後JS操作合併儲存格的,或者是別人寫的太負責了,又不想去理解,所以就自己動手寫了個簡單點的。
其實代碼也不多,思路清晰就基本上可以了。一開始的時候是被colspan蒙了,因為要注意大小寫才可以的。看下代碼,
- <html>
- <head>
- <script type="text/javascript">
- function showRowOrColTable(){
- //建立table
- var table = document.createElement("table");
- var projectid=3; //看圖下合并多少列就寫多少
- table.border = "1";
- var rowIndex = 0;
- var rowStart = 0;
- var rowLength = 2;
- var colIndex = 1;
- var colLength = 2;
- var projectLength=projectid*2;
- for ( var i = 0; i < 5; i++) {
- var row = table.insertRow(i);
- for ( var j = 0; j < projectLength+1; j++) {
- var cell = row.insertCell(j);
- cell.innerHTML = "hello world"; //賦值內容
- }
- }
- for ( var j = 0; j <= rowIndex; j++) {
- table.rows[j].cells[colIndex].colSpan = projectid;
- table.rows[j].cells[projectid*2-1].colSpan = projectid;
- for ( var i = 0; i < projectid - 1; i++) {
- table.rows[j].deleteCell(colIndex+1);
- table.rows[j].deleteCell(3);
- }
- }
- table.rows[rowIndex].cells[rowStart].rowSpan = 2;
- table.rows[rowIndex + 1].deleteCell(0);
- table.rows[0].cells[0].innerHTML = " ";
- table.rows[0].cells[1].innerHTML = "個人得分";
- table.rows[0].cells[2].innerHTML = "個人準確率";
- table.rows[1].cells[0].innerHTML = "第一";
- table.rows[1].cells[1].innerHTML = "第二";
- table.rows[1].cells[2].innerHTML = "第一";
- table.rows[1].cells[3].innerHTML = "第二";
- var _row=table.rows[1];
- document.getElementById("table").appendChild(table);
- }
-
- </script>
- </head>
- <body onLoad="showRowOrColTable()">
- <div id="table"></div>
- </body>
- </html>
650) this.width=650;" src="http://www.bkjia.com/uploads/allimg/131228/12021A415-0.jpg" border="0" alt="" />
本文出自 “Just do it” 部落格,請務必保留此出處http://davenzeng.blog.51cto.com/3896952/1128284