如何將給定的數(shù)據(jù)動(dòng)態(tài)加入到創(chuàng)建的表格中?相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。
創(chuàng)建 table + thead + tbody
創(chuàng)建 tr + th
創(chuàng)建每一行的 tr + td
加到頁(yè)面中
注:最后再加到頁(yè)面中的原因是每將一個(gè)元素加到頁(yè)面一次,頁(yè)面便會(huì)刷新一次,因此先在內(nèi)存中創(chuàng)建好表格再一次性的加到頁(yè)面中,頁(yè)面只需刷新一次,減少性能的損失。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body></body><script> var data = [ { name : "jim1", age : 18, gender : "male"}, { name : "jim2", age : 19, gender : "female"}, { name : "jim3", age : 20, gender : "female"}, { name : "jim4", age : 21, gender : "male"} ]; function createElement( tag ) { return document.createElement( tag ); } var table = createElement( "table" ); var thead = createElement( "thead" ); var tbody = createElement( "tbody" ); table.appendChild( thead ); table.appendChild( tbody ); var trhead = createElement( "tr" ); thead.appendChild( trhead ); for ( var k in data[ 0 ] ){ th = createElement( "th" ); th.appendChild( document.createTextNode( k ) ); trhead.appendChild( th ); } for ( var i = 0; i < data.length; i++){ var tr = createElement( "tr" ); for ( var j in data[ i ]){ td = createElement( "td" ); td.appendChild( document.createTextNode( data[i][j] )); tr.appendChild( td ); } tbody.appendChild( tr ); } //table.setAttribute("border","1px"); //或直接設(shè)置table.border = "1px";兩者等價(jià)。 table.border = "1px"; table.cellspadding = 0; table.setAttribute("align","center"); table.style.textAlign = "center"; table.setAttribute("borderColor","skyBlue"); table.setAttribute("cellspacing",0); document.body.appendChild( table );</script></html>
看完上述內(nèi)容,你們掌握如何將給定的數(shù)據(jù)動(dòng)態(tài)加入到創(chuàng)建的表格中的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)網(wǎng)站制作公司行業(yè)資訊頻道,感謝各位的閱讀!
網(wǎng)站名稱:如何將給定的數(shù)據(jù)動(dòng)態(tài)加入到創(chuàng)建的表格中-創(chuàng)新互聯(lián)
網(wǎng)站網(wǎng)址:http://www.2m8n56k.cn/article40/dgheho.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供營(yíng)銷型網(wǎng)站建設(shè)、云服務(wù)器、品牌網(wǎng)站建設(shè)、建站公司、網(wǎng)站設(shè)計(jì)、網(wǎng)站內(nèi)鏈
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:[email protected]。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容