企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
输入信息,点击添加自动添加到表格 ``` <style> table, tr, th, td { border: 1px solid #ccc; } tr { height: 40px; } table { border-collapse: collapse; width: 630px; text-align: center; margin: 20px auto; } thead { background-color: yellowgreen; } fieldset { width: 600px; margin: 0 auto; } input { height: 20px; } </style> <div id="app"> <!-- 第一部分:输入信息 --> <fieldset> <legend>学生录入系统</legend> <p> <span>姓名:</span> <input type="text" name="username" class="username"> </p> <p> <span>年龄:</span> <input type="text" name="age" class="age"> </p> <p> <span>性别:</span> <select name="sex" id="sex"> <option value="男">男</option> <option value="女">女</option> </select> </p> <p> <span>手机:</span> <input type="text" name="phone" class="phone"> </p> <p> <button id="but">确认提交</button> </p> </fieldset> <!-- 第二部分:信息展示 --> <table> <thead> <tr> <th>姓名</th> <th>年龄</th> <th>性别</th> <th>手机</th> <th>删除</th> </tr> </thead> <tbody class="tbody"> <!-- <tr> <td>张三</td> <td>18</td> <td>男</td> <td>15511111111</td> <td>删除</td> </tr> --> </tbody> </table> </div> <script> // 逻辑:1.添加信息并展示 2.删除操作 // 先把数据push到一个数组当中,然后对数组进行遍历(对tr的循环,拼接之后,赋值给tbody的innerHTML) let sex = document.getElementById('sex'); let but = document.getElementById('but'); let input = document.getElementsByTagName('input'); let tbody = document.getElementsByTagName('tbody')[0]; // 模拟一个数据 // let stus = [{name:"李四",age:19,sex:"男",phone:15512344321}]; let stus = []; // 1.提交 拼接一个对象,作为数组的元素 but.onclick = function () { let obj = { name: input[0].value, age: input[1].value, sex: sex.value, phone: input[2].value }; stus.push(obj); console.log(stus); // 2.对数组进行遍历 let tr = ''; stus.forEach((item, index) => { tr += "<tr class='newTr'>" + "<td>"+item.name+"</td>" + "<td>"+item.age+"</td>" + "<td>"+item.sex+"</td>" + "<td>"+item.phone+"</td>" + "<td onclick='del("+index+")'>删除</td>" + "</tr>"; }); tbody.innerHTML = tr; } // 3.删除操作 function del(index){ // 3.1 删除数组中的这条信息 stus.splice(index,1); // 3.2 删除DOM元素 // tbody.removeChild(该条信息的tr); let res = document.getElementsByClassName('newTr')[index]; tbody.removeChild(res); } </script> ``` 效果图: ![](https://img.kancloud.cn/9e/d2/9ed2d44217f1a8891fc00344ffdcec6b_718x430.png)