<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <!-- <script src="/js/layui.js"></script> --> <link rel="stylesheet" href="/js/NES.css"> <style> </style> </head> <body> <div class="nes-table-responsive"> <table class="nes-table is-bordered is-centered"> <thead> <tr> <td>姓名</td> <td>年龄</td> <td>性别</td> <td>删除</td> </tr> </thead> <tbody> </tbody> </table> </div> </body> </html> <script> let vewData=[ { name:'张三', age:'18', gender:'男' }, { name:'武器大师', age:'46', gender:'男' }, { name:'不详之刃', age:'19', gender:'女' }, { name:'瑞萌萌', age:'20', gender:'女' } ];
//获取tbody的DOM对象 let tdby=document.querySelector('tbody');
//根据数组长度循环创建tr for (let i = 0; i < vewData.length; i++) { let tr=document.createElement('tr');
//根据数组对象中的数据循环创建td并赋值 for (const key in vewData[i]) { let td= document.createElement('td'); td.innerHTML=vewData[i][key]; tr.appendChild(td); }
//最后创建删除按钮并追加 let detr=document.createElement('td'); let btn=document.createElement('button'); btn.innerHTML='删除'; detr.appendChild(btn); tr.appendChild(detr); tdby.appendChild(tr); }
//获取tbody中的所有按钮DOM对象 let btns=tdby.querySelectorAll('button');
//循环绑定点击事件 for (let i = 0; i < btns.length; i++) { btns[i].onclick=function() { //获取当前按钮的父级的父级DOM也就是tr let tr= this.parentNode.parentNode;
//再获取tr的父级 let tbodys=td.parentNode; //删除对应的tr tbodys.removeChild(tr); } } </script>
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/279398.html