表格的创建于删除
[html]<!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=gb2312" />
<title>无标题文档</title>
<style type="text/css">
table{
border:#0033FF 1px solid;
width:600px;
border-collapse:collapse;
}
table td{
border:#0033FF 1px solid;
padding:10px;
}
</style>
<script type="text/javascript">
function crtTable_1()
{
/*var tabNode = document.createElement("table");
var tbdNode = document.createElement("tbody");
var trNode = document.createElement("tr");
var tdNode = crtNode("td");
trNode.appendChild(tdNode);
tbdNode.appendChild(trNode);
*/
//创建一个表格对象
var tabNode = document.createElement("table");
//通过表格对象的insertRow方法创建行
var trNode = tabNode.insertRow();
//创建单元格,通过行对象的insertCell方法创建
var tdNode = trNode.insertCell();
//给单元格添加一些内容
tdNode.innerHTML = "一个单元格";
//document.body.appendChild(tabNode);
var divNode = document.getElementById("divid");
divNode.appendChild(tabNode);
}
//简化document.createElement代码的方法
function crtNode(name)
{
return document.createElement(name);
}
function crtTable()
{
var tabNode = document.createElement("table");
tabNode.setAttribute("id", "tabid");//给表格对象添加一个id属性
var rowNum = document.getElementsByName("rownum")[0].value;
var colNum = document.getElementsByName("colnum")[0].value;
for(var x = 1; x <= rowNum; x++)
{
var trNode = tabNode.insertRow();
for(var y = 1; y <= colNum; y++)
{
var tdNode = trNode.insertCell();
tdNode.innerHTML = x + "--" + y;
}
}
document.getElementById("divid").appendChild(tabNode);
document.getElementsByName("crtBut")[0].disabled = true;
}
function delRow()
{
var tabNode = document.getElementById("tabid");
if(tabNode == null)
{
alert("表格不存在");
return;
}
var rowNum = document.getElementsByName("delrow")[0].value;
if(rowNum >= 1 && rowNum <= tabNode.rows.length)
{
tabNode.deleteRow(rowNum - 1);
}
else
{
alert("要删除的行数不存在");
}
}
function delCol()
{
//删除列:其实就是删除每一行中指定位置的单元格
var tabNode = document.getElementById("tabid");
if(tabNode == null)
{
alert("表格不存在");
return;
}
var colNum = document.getElementsByName("delcol")[0].value;
var trs = tabNode.rows;//获取行的集合
if(colNum >= 1 && colNum <= trs[0].cells.length)
{
for(var x = 0; x < trs.length; x++)
{
trs[x].deleteCell(colNum - 1);
}
}
else
{
alert("要删除的列数不存在");
}
}
</script>
</head>
<body>
行数:<input type="text" name="rownum" /><br />
列数:<input type="text" name="colnum" /><br />
<input type="button" name="crtBut" value="创建表格" onclick="crtTable()" />
<br />
<hr />
<input type="text" name="delrow" /><input type="button" value="删除行" onclick="delRow()" /><br />
<input type="text" name="delcol" /><input type="button" value="删除列" onclick="delCol()" /><br />
<div id="divid">
</div>
</body>
</html>
补充:web前端 , HTML/CSS ,