例子,js动态创建表格的实现代码。
<!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>
<title>动态创建表格-删除行列--www.jb200.com</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>