<html> <head> <style type="text/css"> table{ border:#afccdd 1px solid; width;500px; border-collapse:collapse; } table td{ border:#afccdd 1px solid; padding:5px; } </style> </head> <body> <script type="text/javascript"> function cretable(){ var hang = document.getElementsByName("hang")[0]; var rownum = parseInt(hang.value); var lie = document.getElementsByName("lie")[0]; var cellnum = parseInt(lie.value); var otabNode = document.createElement("table"); for(var x =1;x<=hang.value;x++){ var otrNode = otabNode.insertRow(); for(var y =1;y<=lie.value;y++){ var otdNode = otrNode.insertCell(); otdNode.innerHTML="<font color='green'>java</font>"; } } document.getElementsByTagName("div")[0].appendChild(otabNode); document.getElementsByName("cretab")[0].disabled=true; //按钮属性disabled=true使按钮只能执行一次就变灰 } </script> 行:<input name="hang" type="text" value="" /> 列:<input name="lie" type="text" value="" /> <input type="button" value="创建表格" name="cretab" onclick="cretable()"/> <div></div> </body> </html>
思路:
1、创建html标签
2、编写css样式
3、创建table节点对象
4、创建tr节点对象
5、创建td节点对象(如果不适用table对象中的方法insertRow();就需要产生关系;但是原理都一样)
6、将table节点对象加入到div标签中
<html> <head> <style type="text/css"> table{ border:#ccff00 1px solid; color:#ccff00; background-color:#adddfa; } </style> </head> <body> <div></div> <input type="button" value="添加表格" name="but" onclick="cretable()"/> <script type="text/javascript"> function cretable(){ var tabNode = document.createElement("table"); var tdyNode = document.createElement("tbody"); var trNode = document.createElement("tr"); var tdNode = document.createElement("td"); tdNode.innerHTML="javascript"; trNode.appendChild(tdNode); tdyNode.appendChild(trNode); tabNode.appendChild(tdyNode); document.getElementsByTagName("div")[0].appendChild(tabNode); } </script> </body> </html>