使用Javascript动态增加,删除表格(使用DHTML对象模型)
此种方式只能删除表格的最后一行,如果需要删除指定行,需要使用W3C的对象模型,因为每次删除完表格行后,其他使用DHTML对象模型的行的index都会重新变化,也就是说我原来有5行0,1,2,3,4 删除第3行是没有问题的,但删除后原来序号为4的行,就变成3了,使用deleteRow(4)就会报错
<
html
>
< meta http-equiv ="Content-Type" content ="text/html; charset=gb2312" />
< head >
< script language ="javascript" >
function deleteRow(index){
var tableObj = document.getElementById( " mytable " );
tableObj.deleteRow(tableObj.rows.length - 1 );
}
function addRow(){
var tableObj = document.getElementById( " mytable " );
var newRowObj = tableObj.insertRow(tableObj.rows.length);
var newColName = newRowObj.insertCell(newRowObj.cells.length);
var newColAge = newRowObj.insertCell(newRowObj.cells.length);
var newColButton = newRowObj.insertCell(newRowObj.cells.length);
newColName.innerHTML = document.getElementById( " newName " ).value;
newColAge.innerHTML = document.getElementById( " newAge " ).value;
newColButton.innerHTML = ' <input type="button" value="删除" οnclick="deleteRow();"> ' ;
}
</ script >
</ head >
< body >
< table width ="100%" id ="mytable" border ="0" cellspacing ="0" cellpadding ="0" >
< tr >
< td > 姓名 </ td >
< td > 年龄 </ td >
< td > 操作 </ td >
</ tr >
</ table >
< input type ="text" name ="name" id ="newName" />
< input type ="text" name ="age" id ="newAge" />
< input type ="button" onclick ="addRow();" value ="新增" />
</ body >
</ html >
< meta http-equiv ="Content-Type" content ="text/html; charset=gb2312" />
< head >
< script language ="javascript" >
function deleteRow(index){
var tableObj = document.getElementById( " mytable " );
tableObj.deleteRow(tableObj.rows.length - 1 );
}
function addRow(){
var tableObj = document.getElementById( " mytable " );
var newRowObj = tableObj.insertRow(tableObj.rows.length);
var newColName = newRowObj.insertCell(newRowObj.cells.length);
var newColAge = newRowObj.insertCell(newRowObj.cells.length);
var newColButton = newRowObj.insertCell(newRowObj.cells.length);
newColName.innerHTML = document.getElementById( " newName " ).value;
newColAge.innerHTML = document.getElementById( " newAge " ).value;
newColButton.innerHTML = ' <input type="button" value="删除" οnclick="deleteRow();"> ' ;
}
</ script >
</ head >
< body >
< table width ="100%" id ="mytable" border ="0" cellspacing ="0" cellpadding ="0" >
< tr >
< td > 姓名 </ td >
< td > 年龄 </ td >
< td > 操作 </ td >
</ tr >
</ table >
< input type ="text" name ="name" id ="newName" />
< input type ="text" name ="age" id ="newAge" />
< input type ="button" onclick ="addRow();" value ="新增" />
</ body >
</ html >
从 <http://blog.csdn.net/daryl715/archive/2008/02/01/2077569.aspx> 插入