本文實例講述了Javascript動態創建表格及刪除行列的方法。分享給大家供大家參考。具體實現方法如下:
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 <!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> <style type="text/css"> body,div { margin:0; padding:0; font-size:14px; } table { margin:0 auto; } td { border:1px solid green; text-align:center; } </style> <script type="text/javascript"> //動態創建表格 function createTable() { var divMain = document.getElementById("divMain"); removeAllChild(divMain); //刪除上次添加的表格 var myTable = document.createElement("table"); myTable.id = "DynamicTable"; var myRow = document.getElementById("myRow").value; var myCol = document.getElementById("myCol").value; var trNode; var tdNode; var strTmp; for (var i = 1; i <= myRow; i++) { trNode = myTable.insertRow(-1); for (var j = 1; j <= myCol; j++) { strTmp ="第"+ i + "行,第"+ j + "列"; tdNode = trNode.insertCell(-1); tdNode.innerHTML = "<a href='javascript:void(0);'>" + strTmp + "</a>"; } } divMain.appendChild(myTable); //把表格添加到div中 //event.srcElement.disabled = "true"; //添加按鈕禁用 } //刪除指定節點下的所有子節點 function removeAllChild(nodeObj) { while (nodeObj.hasChildNodes()) { nodeObj.removeChild(nodeObj.firstChild); } } //刪除行 function DeleteRow() { var rowNum = document.getElementById("delRow").value; var tbl = document.getElementById("DynamicTable"); if (tbl == null) { alert('請先創建表格'); return; } if ((rowNum <= tbl.rows.length) && (rowNum > 0)) { tbl.deleteRow(rowNum-1); } else { alert('請輸入一個有效的行!'); } } //刪除列 function DeleteCol() { var colNum = document.getElementById("delCol").value; var tbl = document.getElementById("DynamicTable"); if (tbl == null) { alert('請先創建表格'); return; } if(tbl.rows.length<=0) { alert('表格不存在行'); return; } if ((colNum <= tbl.rows[0].cells.length) && (colNum > 0)) { for (var i = 0; i < tbl.rows.length; i++) { tbl.rows[i].deleteCell(colNum - 1); } } else { alert('指定列不存在'); } } </script> </head> <body> 請輸入行數<input type="text" id="myRow" />,請輸入列數 <input type="text" id="myCol" /><br /> <input type="button" value="創建表格" onclick="createTable()" /><br /> <input type="text" id="delRow" /><input type="button" value="刪除行" onclick="DeleteRow()" /><br /> <input type="text" id="delCol" /><input type="button" value="刪除列" onclick="DeleteCol()" /><br /> <div id="divMain"> </div> </body> </html>希望本文所述對大家的javascript程序設計有所幫助。