This article mainly introduces JavaScript to realize dynamic addition and deletion of tables, which can realize the function of adding and deleting data in the table. It is of great practical value. If you are interested, you can learn about it
above Fill in the text box with "Name/Email/Age" to dynamically add or delete cells in the table below
Effect:
1 . Html code:
<body> <p align="center" id="info"> 姓名 : <input type="text" id = "username"> Email : <input type="text" id = "email"> 年龄 : <input type="text" id = "age"> </p> <p align="center"><input type="button" value="添加" onclick="addRow()"></p> <hr> <table align="center" border="1" id = "testTble" style="width: 60%;text-align: center;border:1px solid lightgreen"> <tr> <td>姓名</td> <td>Email</td> <td>年龄</td> <td>操作</td> </tr> </table>
2. JavaScript code:
<script type="text/javascript"> // 三个文本框 // 一个添加按钮 按钮实现功能 添加信息到表格中 // 一个表格,行数动态增加的 function addRow() { // 获取input元素节点数组 var inputNodes = document.getElementsByTagName("input"); var str = new String(inputNodes[0].value); var str1 = new String(inputNodes[1].value); var str2 = new String(inputNodes[2].value); if ((str.length > 0) && (str1.length > 0) && (str2.length > 0)) { //添加一行 insertRow() 方法用于在表格中的指定位置插入一个新行 var newTr = testTble.insertRow(); //添加四列 sertCell() 方法用于在 HTML 表的一行的指定位置插入一个空的 <td> 元素 var newTd0 = newTr.insertCell(); var newTd1 = newTr.insertCell(); var newTd2 = newTr.insertCell(); var newTd3 = newTr.insertCell(); //分别给每一列赋值 newTd0.innerText= inputNodes[0].value; newTd1.innerText= inputNodes[1].value; newTd2.innerText= inputNodes[2].value; newTd3.innerHTML = "<input type='button' value='删除' onclick='deleteTable(this)'>"; } else { alert("请先把信息填写完整!"); return; } } function deleteTable(r) { //获取当前表格行号 var i = r.parentNode.parentNode.rowIndex; //调用deleteRow()删除本行 document.getElementById('testTble').deleteRow(i); } </script>
The above is the detailed content of Detailed introduction to the implementation of JavaScript dynamic addition and deletion of tables. For more information, please follow other related articles on the PHP Chinese website!