js動(dòng)態(tài)生成表格(節(jié)點(diǎn)操作)
本文實(shí)例為大家分享了js動(dòng)態(tài)生成表格的具體代碼,供大家參考,具體內(nèi)容如下
針對(duì)DOM節(jié)點(diǎn)操作,該案例效果圖如下(代碼量不多,就沒(méi)有結(jié)構(gòu)與行為相分離):
原生js實(shí)現(xiàn)(注釋里面解釋了做法):
<!DOCTYPE html><html> <head> <meta charset='utf-8'> <title></title> <style type='text/css'> 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; } </style> </head> <body> <table cellspacing='0'> <thead> <tr> <th>姓名</th> <th>科目</th> <th>成績(jī)</th> <th>操作</th> </tr> </thead> <tbody> </tbody> </table> </body> <script type='text/javascript'> //因?yàn)槔锩娴膶W(xué)生數(shù)據(jù)都是動(dòng)態(tài)的,我們需要js動(dòng)態(tài)生成 這里我們需要模擬數(shù)據(jù),自己定義好數(shù)據(jù) // 數(shù)據(jù)我們采取對(duì)象形式儲(chǔ)存 //1 先準(zhǔn)備好學(xué)生的數(shù)據(jù) //2 所有數(shù)據(jù)都是放到tbody里面(多少人,多少行) var datas = [{ name: ’劉舒新’, subject: ’JavaScript’, score: ’100’ }, { name: ’宋祥隆’, subject: ’JavaScript’, score: ’80’ }, { name: ’崔健’, subject: ’JavaScript’, score: ’90’ }, { name: ’郄海淼’, subject: ’JavaScript’, score: ’70’ } ]; //console.log(datas.length); var tbody = document.querySelector(’tbody’); for (var i = 0; i < datas.length; i++) { //創(chuàng)建行 trs = document.createElement(’tr’); tbody.appendChild(trs); //創(chuàng)建單元格 td的數(shù)量取決于每個(gè)對(duì)象里面的屬性個(gè)數(shù) for(var k in datas[i]){ //創(chuàng)建單元格 var td=document.createElement(’td’); //把對(duì)象里面的屬性值 給td //console.log(datas[i][k]); td.innerHTML=datas[i][k]; trs.appendChild(td); } //創(chuàng)建操作刪除單元格 var td=document.createElement(’td’); td.innerHTML=’<a href='javascript:;' rel='external nofollow' >刪除</a>’ trs.appendChild(td); } //刪除操作 var a=document.querySelectorAll(’a’); for(var i=0;i<a.length;i++){ a[i].onclick=function(){ tbody.removeChild(this.parentNode.parentNode); } } </script></html>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
