效果图:
代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>js表格添加删除</title> <style> *{ margin: 0; padding: 0; } .top,.top1{ width: 200px; height: 40px; font-size: 30px; font-weight: 900; color: #000; margin-bottom: 20px; } .right{ width: 300px; height: 200px; position: relative; margin: 30px auto; display: none; } .left{ position: absolute; top: 30px; left: 50px; } input{ outline: none; } span{ color: blue; text-decoration: underline; font-size: 16px; padding-left: 5px; cursor: pointer; } .left table tbody tr td{ color: #000; font-size: 16px; } </style> </head> <body> <div class="right"> <div class="top">表格添加</div> 姓名:<input type="text" class="name" placeholder="请输入姓名"><br> 年龄:<input type="text" class="age" placeholder="请输入年龄"><br> 性别:<input type="text" class="sex" placeholder="请输入性别"><br> <button style="cursor: pointer;">添加</button> </div> <div class="left"> <div class="top1">内容展示<span>添加</span></div> <table border=1 cellspacing="0" width=‘400px‘ height=‘30px‘ bgcolor=‘#fff‘> <thead> <tr> <th>姓名</th> <th>年龄</th> <th>性别</th> <th>操作</th> </tr> </thead> <tbody> </tbody> </table> </div> </body> </html> <script> var left = document.querySelector(".left") var right = document.querySelector(".right") var btn = document.querySelector("button") var span = document.querySelector(".left .top1>span") var tbody = document.querySelector("tbody"); span.onclick =()=>{ left.style.display="none" right.style.display="block" } btn.onclick=()=>{ var name = document.querySelector(".name").value; var age = document.querySelector(".age").value; var sex = document.querySelector(".sex").value; var oTd = document.createElement("td"); var oTab = document.getElementsByTagName("table")[0]; if(name == ‘‘){ alert("请输入姓名!!!"); return false; } if(age == ‘‘){ alert("请输入年龄!!!"); return false; } if(sex == ‘‘){ alert("请输入性别!!!"); return false; } var tr = document.createElement("tr"); var nameTd = document.createElement("td"); nameTd.innerText = name; tr.appendChild(nameTd); var ageTd = document.createElement("td"); ageTd.innerText = age; tr.appendChild(ageTd); var sexTd = document.createElement("td"); sexTd.innerText = sex; tr.appendChild(sexTd); document.querySelector("tbody").appendChild(tr); document.querySelector(".name").value = ‘‘; document.querySelector(".age").value = ‘‘; document.querySelector(".sex").value = ‘‘; left.style.display="block" right.style.display="none" var oTd = document.createElement("td"); var oBtn = document.createElement("button"); oBtn.innerHTML = "删除"; oTd.appendChild(oBtn); tr.appendChild(oTd); oTab.appendChild(tr); oBtn.onclick = function(){ oTab.removeChild(tr); } } function getStyle(ele,attr){ if(window.getComputedStyle){ return window.getComputedStyle(ele)[attr]; }else{ return ele.currentStyle[attr]; } } </script>
原文:https://www.cnblogs.com/biben/p/13335035.html