<!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> </head> <style> </style> <body> <!-- 2. 根据结构和数据创建表格并加删除功能 指定的结构: --> <table border=1 width="500"> <thead> <tr id="a"> <th>序号</th> <th>姓名</th> <th>年龄</th> <th>性别</th> <th>成名绝技</th> <th>操作</th> </tr> </thead> <tbody> </tbody> </table> </body> <script> //删除表格 var arr = [ { name:"令狐冲", age:20, sex:"男", skill:"独孤九剑" }, { name:"东方不败", age:50, sex:"女", skill:"葵花宝典" }, { name:"任我行", age:55, sex:"男", skill:"吸星大法" } ] var tbody = document.querySelector("tbody"); loadHTML() function loadHTML(){ var str =''; for(var i=0;i<arr.length;i++){ var obj = arr[i] str +="<tr><td>" + (i+1) +"</td><td>" + obj.name + "</td><td>" + obj.age + "</td><td>" + obj.sex + "</td><td>" + obj.skill + "</td><td>" + "删除" + "</td></tr>" } var tbody = document.querySelector('tbody'); tbody.innerHTML = str; } addEvent() function addEvent(){ //获取删除的td var tds = document.querySelectorAll('td:last-child'); for(var i=0;i<tds.length;i++){ (function(i){ tds[i].onclick = function(){ arr.splice(i,1) loadHTML() addEvent() } })(i) } } </script> </html>
效果图:点击删除即可删除一行