JavaScript創(chuàng)建表格的方法
本文實(shí)例為大家分享了JavaScript創(chuàng)建表格的具體代碼,供大家參考,具體內(nèi)容如下
<!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'); // 通過(guò) for in 循環(huán)遍歷對(duì)象,得到對(duì)象的屬性,為表頭添加內(nèi)容 for (let i in data[6]) { let th = document.createElement('th'); th.innerText = i; tr.appendChild(th); } table.appendChild(tr); // 通過(guò) forEach 循環(huán)遍歷對(duì)象數(shù)組,為表格添加行 data.forEach((value, index) => { let tr = document.createElement('tr'); // 通過(guò) for in 循環(huán)遍歷對(duì)象,得到對(duì)象的屬性,給每行添加內(nèi)容 for (let index1 in data[index]) { let td = document.createElement('td'); td.innerText = data[index][index1]; tr.appendChild(td); } table.appendChild(tr); }); //設(shè)置表格的對(duì)齊屬性,和邊框?qū)傩? table.setAttribute('text-align', 'right'); table.setAttribute('border','1'); return table; } document.querySelector('div').appendChild(buildTable(MOUNTAINS));</script></body></html>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 用xslt+css讓RSS顯示的跟網(wǎng)頁(yè)一樣漂亮2. ASP.NET MVC把數(shù)據(jù)庫(kù)中枚舉項(xiàng)的數(shù)字轉(zhuǎn)換成文字3. 《CSS3實(shí)戰(zhàn)》筆記--漸變?cè)O(shè)計(jì)(一)4. 測(cè)試模式 - XSL教程 - 55. Ajax實(shí)現(xiàn)異步加載數(shù)據(jù)6. 教你JS更簡(jiǎn)單的獲取表單中數(shù)據(jù)(formdata)7. ASP.NET Core自定義中間件的方式詳解8. html5手機(jī)觸屏touch事件介紹9. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫(huà)特效10. 讓chatgpt將html中的圖片轉(zhuǎn)為base64方法示例
