本来觉得这个挺好做的,可是当自己动手写的时候,发现会出现各种各样的问题。。。若不是同学问我,估计还真的把这些给忘记了呢。。。不多说,上代码。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"/>
<title>无标题文档</title>
</head>
<body>
<input type="button" value="增加一行" onclick="addRow()"/> <input type="button" value="删除一行" onclick="deleteRow()"/>
<input type="button" value="增加一列" onclick="addCol()"/> <input type="button" value="删除一列" onclick="deleteCol()"/>
<script type="text/javascript">
var table = document.createElement('table');
table.id = 'testTable';
table.border = 1;
table.width = "50%";
var tbody = document.createElement('tbody');
table.appendChild(tbody);
//添加行
var addRow = function () {
var rowLength = table.rows.length;
tbody.insertRow(rowLength);
var colLength = table.rows[0].cells.length;
if (colLength < 1) {
tbody.rows[0].insertCell(0);
tbody.rows[0].cells[0].appendChild(document.createTextNode('cell0.0'));
} else {
for (var i = 0; i < colLength; i++) {
tbody.rows[rowLength].insertCell(i);
tbody.rows[rowLength].cells[i].appendChild(document.createTextNode('cell' + rowLength + '.' + i));
}
}
}
//删除行
function deleteRow() {
var rowLength = table.rows.length;
if (rowLength < 1) {
alert('table is null');
} else {
table.deleteRow(rowLength - 1);
}
}
//增加列
function addCol() {
var rowLength = table.rows.length;
var colLength;
if (rowLength < 1) {
tbody.insertRow(0);
tbody.rows[0].insertCell(0);
tbody.rows[0].cells[0].appendChild(document.createTextNode('cell0.0'));
} else {
colLength = table.rows[0].cells.length;
for (var i = 0; i < rowLength; i++) {
tbody.rows[i].insertCell(colLength);
tbody.rows[i].cells[colLength].appendChild(document.createTextNode('cell' + i + '.' + colLength));
}
}
}
//删除列
function deleteCol() {
var rowLength = table.rows.length;
var colLength;
if (rowLength < 1) {
alert('table is null');
} else {
colLength = table.rows[0].cells.length;
if (colLength === 1) {
while (tbody.hasChildNodes()) {
tbody.removeChild(tbody.firstChild);
}
} else {
for (var i = 0; i < rowLength; i++) {
tbody.rows[i].deleteCell(colLength - 1);
}
}
}
}
document.body.appendChild(table);
</script>
</body>
</html>