JavaScript創(chuàng)建表格的方法
本文實例為大家分享了JavaScript創(chuàng)建表格的具體代碼,供大家參考,具體內容如下
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>Title</title></head><body><div id = 'mountains'></div><script> let MOUNTAINS = [ {name: 'Kilimanjaro', height: 5895, place: 'Tanzania'}, {name: 'Everest', height: 8848, place: 'Nepal'}, {name: 'Mount Fuji', height: 3776, place: 'Japan'}, {name: 'Vaalserberg', height: 323, place: 'Netherlands'}, {name: 'Denali', height: 6168, place: 'United States'}, {name: 'Popocatepetl', height: 5465, place: 'Mexico'}, {name: 'Mont Blanc', height: 4808, place: 'Italy/France'} ]; // 創(chuàng)建表格 function buildTable(data) { let table = document.createElement('table'); let tr = document.createElement('tr'); // 通過 for in 循環(huán)遍歷對象,得到對象的屬性,為表頭添加內容 for (let i in data[6]) { let th = document.createElement('th'); th.innerText = i; tr.appendChild(th); } table.appendChild(tr); // 通過 forEach 循環(huán)遍歷對象數(shù)組,為表格添加行 data.forEach((value, index) => { let tr = document.createElement('tr'); // 通過 for in 循環(huán)遍歷對象,得到對象的屬性,給每行添加內容 for (let index1 in data[index]) { let td = document.createElement('td'); td.innerText = data[index][index1]; tr.appendChild(td); } table.appendChild(tr); }); //設置表格的對齊屬性,和邊框屬性 table.setAttribute('text-align', 'right'); table.setAttribute('border','1'); return table; } document.querySelector('div').appendChild(buildTable(MOUNTAINS));</script></body></html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. Ajax常用封裝庫——Axios的使用2. jsp網頁實現(xiàn)貪吃蛇小游戲3. jsp+servlet簡單實現(xiàn)上傳文件功能(保存目錄改進)4. CSS Hack大全-教你如何區(qū)分出IE6-IE10、FireFox、Chrome、Opera5. 使用Blazor框架實現(xiàn)在前端瀏覽器中導入和導出Excel6. ASP.NET MVC使用Identity增刪改查用戶7. 使用Python第三方庫pygame寫個貪吃蛇小游戲8. 在服務器端的XSLT過程中的編碼問題9. Python中selenium庫的用法詳解10. 微信小程序授權登錄的最新實現(xiàn)方案詳解(2023年)
