<!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>动态渲染页面</title> <style> div{ position: relative; left: 10%; top: 50%; margin: 50px auto; } table{ border-collapse: collapse; border: 2px solid yellowgreen; border-radius: 20px;
} th,td{ height: 20px; width: 100px; border: 1px solid burlywood; font-size: 16px; text-align: center; padding: 10px 40px; color: white; background-color: skyblue; } button{ position: relative; left: 10px; font-size: 16px; color: white; background-color: skyblue; border: 2px solid orangered; cursor: pointer; border-radius: 5px;
} </style> </head> <body> <div> <table> <thead> <tr><th>ID</th><th>姓名</th><th>年龄</th></tr> </thead> <tbody> </tbody> <tfoot> <tr><td colspan="3"><button>生成数据</button></td></tr> </tfoot> </table> </div>
<script> let users = [ {id: 1, name: '前端小灰狼', age: 28 }, {id: 2, name: '前端小灰', age: 27 }, {id: 3, name: '前端小', age: 26 }, {id: 4, name: '前端', age: 25 }, {id: 5, name: '前', age: 24 }, ] let bnt = document.querySelector('button'); let tbody = document.querySelector('tbody');
bnt.onclick = function(){ users.forEach(function(item){ let tr = document.createElement('tr');
for(let i in item){ let td = document.createElement('td'); td.innerText = item[i]; tr.appendChild(td); } tbody.appendChild(tr); }) }
</script> </body> </html>
|