JavaScript動(dòng)態(tài)生成表格的示例
要求:
HTML標(biāo)簽只寫一行表頭通過(guò)JS來(lái)寫動(dòng)態(tài)的表格(有多少組數(shù)據(jù),就自動(dòng)創(chuàng)建多少行表格)為學(xué)習(xí)和演示,采用固定的數(shù)據(jù),不涉及調(diào)用后臺(tái)數(shù)據(jù)
代碼實(shí)現(xiàn):HTML內(nèi)容:
<table cellspacing='0'> <thead> <tr> <th>姓名</th> <th>科目</th> <th>成績(jī)</th> <th>操作</th> </tr> </thead> <tbody></tbody></table>
CSS內(nèi)容:
table { width: 500px; margin: 100px auto; border-collapse: collapse; text-align: center;}td,th { border: 1px solid #333;}thead tr { height: 40px; background-color: #ccc;}
JS內(nèi)容:
// 1.先準(zhǔn)備好學(xué)生的數(shù)據(jù),用數(shù)組形式儲(chǔ)存,每個(gè)數(shù)組元素是一個(gè)對(duì)象var datas = [{ name: ’張三’, subject: ’JavaScript’, score: 100}, { name: ’李四’, subject: ’JavaScript’, score: 98}, { name: ’王五’, subject: ’JavaScript’, score: 99}, { name: ’趙六’, subject: ’JavaScript’, score: 88}, { name: ’哈哈’, subject: ’JavaScript’, score: 0}];// 2. 往tbody 里面創(chuàng)建行: 有幾個(gè)人(通過(guò)數(shù)組的長(zhǎng)度)我們就創(chuàng)建幾行var tbody = document.querySelector(’tbody’);for (var i = 0; i < datas.length; i++) { // 外面的for循環(huán)管行 tr // 1. 創(chuàng)建 tr行 var tr = document.createElement(’tr’); tbody.appendChild(tr); // 2. 行里面創(chuàng)建單元格(跟數(shù)據(jù)有關(guān)系的3個(gè)單元格) td 單元格的數(shù)量取決于每個(gè)對(duì)象里面的屬性個(gè)數(shù) for循環(huán)遍歷對(duì)象 datas[i] for (var k in datas[i]) { // 里面的for循環(huán)管列 td // 創(chuàng)建單元格 var td = document.createElement(’td’); // 把對(duì)象里面的屬性值 datas[i][k] 給 td // console.log(datas[i][k]); td.innerHTML = datas[i][k]; tr.appendChild(td); } // 3. 創(chuàng)建有刪除2個(gè)字的單元格 var td = document.createElement(’td’); td.innerHTML = ’<a href='javascript:;' rel='external nofollow' >刪除</a>’; tr.appendChild(td);}// 4. 刪除操作var as = document.querySelectorAll(’a’);for (var i = 0; i < as.length; i++) { as[i].onclick = function() { // 點(diǎn)擊a刪除 當(dāng)前a所在的行(a父節(jié)點(diǎn)的父節(jié)點(diǎn)) node.removeChild(child) tbody.removeChild(this.parentNode.parentNode) }}// for(var k in obj) {// k 得到的是屬性名// obj[k] 得到是屬性值// }
實(shí)現(xiàn)效果:
點(diǎn)擊刪除按鈕,相應(yīng)的行會(huì)刪除。點(diǎn)擊刪除“張三”的數(shù)據(jù):
以上就是JavaScript動(dòng)態(tài)生成表格的示例的詳細(xì)內(nèi)容,更多關(guān)于JavaScript 生成表格的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 基于 Python 實(shí)踐感知器分類算法2. Python如何批量生成和調(diào)用變量3. ASP.Net Core對(duì)USB攝像頭進(jìn)行截圖4. ajax動(dòng)態(tài)加載json數(shù)據(jù)并詳細(xì)解析5. Python 中如何使用 virtualenv 管理虛擬環(huán)境6. python利用opencv實(shí)現(xiàn)顏色檢測(cè)7. 通過(guò)CSS數(shù)學(xué)函數(shù)實(shí)現(xiàn)動(dòng)畫特效8. ASP.Net Core(C#)創(chuàng)建Web站點(diǎn)的實(shí)現(xiàn)9. ASP.NET MVC實(shí)現(xiàn)橫向展示購(gòu)物車10. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無(wú)效問(wèn)題
