<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style> #t1 tr td{height: 30px; width: 100px;} .box0{background-color: #0000FF;} .box1{background-color: red;} </style> <script> window.onload=function(){ var oRow=document.getElementById("row"); var oCol=document.getElementById("col"); var oBtn=document.getElementById("btn1"); var oT1=document.getElementById("t1"); //給表格上的刪除按鈕 oT1.onclick=function(ev){ var e=ev||window.event; var target=e.target||window.event.srcElement; if(target.nodeName.toLowerCase()=="button"){ oT1.removeChild(target.parentNode.parentNode); } } oBtn.onclick=function(){ if(!oRow.value ||!oCol.value){ alert("請輸入對應的行列,生成表格"); }else{ for(var i=0;i<oRow.value;i++){ var oTr=document.createElement("tr"); oTr.className="box"+(i%2); for(var j=0;j<oCol.value;j++){ var oTd=document.createElement("td"); oTr.appendChild(oTd); } var oClose=document.createElement("td");//附加刪除 oClose.innerHTML="<button>刪除</button>"; oT1.appendChild(oTr); oTr.appendChild(oClose); } } } } </script> </head> <body> <input type="text" placeholder="行" id="row"/> <input type="text" placeholder="列" id="col"/> <button id="btn1">生成</button> <table id="t1" border="1"> </table> </body> </html>