<html> <head> <title>Adding and Removing Rows from a table using DHTML and JavaScript</title> <script language="javascript"> //add a new row to the table function addRow() { //add a row to the rows collection and get a reference to the newly added row var newRow = document.all("tblGrid").insertRow(); newRow.setAttribute("className","tr2");//设置增加行的class属性 newRow.setAttribute("align","center");//设置增加行的align属性 //add 3 cells (<td>) to the new row and set the innerHTML to contain text boxes var oCell = newRow.insertCell(); oCell.innerHTML = "<input type='text' name='t1'>"; oCell = newRow.insertCell(); oCell.innerHTML = "<input type='text' name='t2'>"; oCell = newRow.insertCell(); oCell.innerHTML = "<input type='button' value='Delete' οnclick='removeRow(this);'/>"; } //deletes the specified row from the table function removeRow(src) { var oRow = src.parentElement.parentElement; document.all("tblGrid").deleteRow(oRow.rowIndex); } </script> </head> <body> Demo of a simple table grid that allows adding and deleting rows using DHTML and Javascript <table id="tblGrid" style="table-layout:fixed" border="1"> <tr> <td width="150px">姓名</td> <td width="150px">年龄</td> <td width="250px">操作</td> </tr> <tr> <td><input type="text" name="t1" /></td> <td><input type="text" name="t2" /></td> <td align="center"><input type="button" value="Delete" οnclick="removeRow(this);" /></td> </tr> </table> <hr> <input type="button" value="Add Row" οnclick="addRow();" /> <hr> </a> </body> </html>
上面的代码实现了,对table的增加跟删除,在具体项目中的应用,需要通过Ajax的异步调用,通过后台传过的数据,动态的把值赋给单元格,代码上的删除只是删除的单元行,没有真正的删除数据,这样就可以做局部刷新(异步删除数据)