<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>增加Table行</title>
</head>
<script>
function addRow(tabId)
{
var tab = document.getElementById(tabId);
//添加一行
var colCount = getColCount(tabId);
var rowCount = getRowCount(tabId);
var newTr = tab.insertRow();
if(0 == rowCount)
{
colCount = 1;
}
for(var i = 0; i < colCount; ++i)
{
var tmp = newTr.insertCell();
tmp.innerHTML = '<input type=text value="">';
}
}
function addCell(tabId)
{
var tab = document.getElementById(tabId);
var rowCount = getRowCount(tabId);
for(var i = 0; i < rowCount;++i)
{
var tmp = tab.rows.item(i).insertCell();
tmp.innerHTML = '<input type=text value="">';
}
}
function delRow(tabId)
{
var rowCount = getRowCount(tabId);
if(rowCount <= 0)
{
return;
}
var tab = document.getElementById(tabId);
tab.deleteRow(rowCount - 1);
}
function delCell(tabId)
{
var tab = document.getElementById(tabId);
var rowCount = getRowCount(tabId);
if(rowCount > 0)
{
var colCount = getColCount(tabId);
if(1 >= colCount)
{
clearTable(tabId);
}
else
{
for ( var i = 0; i < tab.rows.length; i++)
{
tab.rows[i].deleteCell(colCount - 1);
}
}
}
}
function clearTable(tabId)
{
var tab = document.getElementById(tabId);
while(tab.hasChildNodes()){
tab.removeChild(tab.lastChild);
}
}
function getRowCount(tabId)
{
var tab = document.getElementById(tabId) ;
//表格行數
var rows = 0;
if(null != tab.rows)
{
rows = tab.rows.length ;
}
else
{
alert("no rows");
rows = 0;
}
return rows
}
function getColCount(tabId)
{
var tab = document.getElementById(tabId) ;
var cells = 0;
if(null != tab.rows && tab.rows.length > 0)
{
cells = tab.rows.item(0).cells.length;
}
return cells;
}
/*
* 提取一個表單的數據
*/
function formatTableData(tableId ) {
var ret = "";
var t3 = document.getElementById(tableId);
for ( var i = 0; i < t3.rows.length; i++) {
for ( var j = 0; j < t3.rows[i].cells.length; j++) {
ret = ret + t3.rows[i].cells[j].children[0].value + "#";
}
}
alert(ret);
return ret;
}
</script>
<body>
<table id="testTbl" border=1 >
<tr id="tr1">
<td >
<input type=text value="12345"> </input>
</td>
</tr>
<tr id="tr2">
<td ><input type=text value="1bb"> </input> </td>
</tr>
<tr id="tr3">
<td > <input type=text value="1cc"> </input> </td>
</tr>
</table>
<br />
<input type="button" id="add" οnclick="addRow('testTbl');" value="Add Row" />
<input type="button" id="addcel" οnclick="addCell('testTbl');" value="Add Cell" />
<br />
<input type="button" id="delRow" οnclick="delRow('testTbl');" value="remove Row" />
<input type="button" id="delcel" οnclick="delCell('testTbl');" value="remove Cell" />
<br />
<input type="button" id="delcel" οnclick="formatTableData('testTbl');" value="get data" />
</body>
</html>
js 動態操作表格
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.