<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> </head> <body> <form action="" onsubmit="return tijiao(this)"> ID: <input type="text" name="id"><br/> Name: <input type="text" name="name"><br/> Sex : <input type="text" name="sex"><br/> Age : <input type="text" name="age"><br/> City: <input type="text" name="city"><br/> <input type="submit" value="添加"> </form> <table id="mytab" align="center" width="800" border="1"> <tr> <td>ID</td> <td>Name</td> <td>Sex</td> <td>Age</td> <td>City</td> <td>Action</td> </tr> <tr> <td>1</td> <td>Jack</td> <td>人妖</td> <td>18</td> <td>泰国</td> <td><button onclick="del(this)">删除</button></td> </tr> <tr> <td>2</td> <td>Jack</td> <td>人妖</td> <td>18</td> <td>泰国</td> <td><button onclick="del(this)">删除</button></td> </tr> <tr> <td>3</td> <td>Jack</td> <td>人妖</td> <td>18</td> <td>泰国</td> <td><button onclick="del(this)">删除</button></td> </tr> <tr> <td>4</td> <td>Jack</td> <td>人妖</td> <td>18</td> <td>泰国</td> <td><button onclick="del(this)">删除</button></td> </tr> <tr> <td>5</td> <td>Jack</td> <td>人妖</td> <td>18</td> <td>泰国</td> <td><button onclick="del(this)">删除</button></td> </tr> </table> </body> <script type="text/javascript"> var mytab = document.getElementById('mytab'); function tijiao(obj){ //动态创建一行 var row = mytab.insertRow(); //添加单元格 //我们主要将input里面的值写入到表格中 //可以直接获取input里面的值,我们可以通过form表单对下面的Input标签里面的name属性的值来获取相应的内容 row.insertCell().innerHTML = obj.id.value; row.insertCell().innerHTML = obj.name.value; row.insertCell().innerHTML = obj.sex.value; row.insertCell().innerHTML = obj.age.value; row.insertCell().innerHTML = obj.city.value; row.insertCell().innerHTML = '<button onclick="del(this)">删除</button>'; //清空表单 //直接调用重置时间 obj.reset(); //阻止页面提交操作 return false; } function del(obj){ var tr = obj.parentNode.parentNode; tr.parentNode.removeChild(tr); } </script> </html>
点击 "运行实例" 按钮查看在线实例