JavaScript創建表格的方法
本文實例為大家分享了JavaScript創建表格的具體代碼,供大家參考,具體內容如下
<!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'} ]; // 創建表格 function buildTable(data) { let table = document.createElement('table'); let tr = document.createElement('tr'); // 通過 for in 循環遍歷對象,得到對象的屬性,為表頭添加內容 for (let i in data[6]) { let th = document.createElement('th'); th.innerText = i; tr.appendChild(th); } table.appendChild(tr); // 通過 forEach 循環遍歷對象數組,為表格添加行 data.forEach((value, index) => { let tr = document.createElement('tr'); // 通過 for in 循環遍歷對象,得到對象的屬性,給每行添加內容 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. 基于javaweb+jsp實現企業車輛管理系統2. 怎樣才能用js生成xmldom對象,并且在firefox中也實現xml數據島?3. 利用ajax+php實現商品價格計算4. ASP.Net MVC利用NPOI導入導出Excel的示例代碼5. jstl 字符串處理函數6. JSP動態網頁開發原理詳解7. PHP中為什么使用file_get_contents("php://input")接收微信通知8. .Net core Blazor+自定義日志提供器實現實時日志查看器的原理解析9. IOS蘋果AppStore內購付款的服務器端php驗證方法(使用thinkphp)10. XML CDATA是什么?
