利用jQuery创建一个简单的表格,并添加一个简单的删除按钮
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .tb { width: 200px; text-align: center; } </style> </head> <body> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(function () { let arr = [ { id: 2, name: ‘sjl‘, age: 10 }, { id: 3, name: ‘sddl‘, age: 20 }, { id: 5, name: ‘dfjl‘, age: 30 } ] let table = $(‘<table/>‘).addClass(‘tb‘); let th1 = $(‘<th>‘).html(‘编号‘); let th2 = $(‘<th>‘).html(‘名字‘); let th3 = $(‘<th>‘).html(‘年龄‘); let th4 = $(‘<th>‘).html(‘按钮‘); let thead = $(‘<tr/>‘).append(th1).append(th2).append(th3).append(th4); table.append(thead); $(‘body‘).append(table); arr.forEach(r => { let tr = $(‘<tr/>‘); Object.values(r).forEach(v => { let td = $(‘<td/>‘).html(v); tr.append(td); }); let btn = $(‘<button/>‘).html(‘删除‘).addClass(‘del‘); tr.append(btn) table.append(tr) }) $(‘.del‘).click(function(){ if(confirm(‘确定删除吗?‘)) $(this).parents(‘tr‘).remove(); }) }) </script> </body> </html>