What this article brings to you is about dynamically adding given data to the created table (source code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Create table thead tbody
Create tr th
Create tr td for each line
Add to the page
Note: Add it last The reason in the page is that every time an element is added to the page, the page will be refreshed. Therefore, the table is first created in the memory and then added to the page at once. The page only needs to be refreshed once, reducing the loss of performance.
<!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"); //或直接设置table.border = "1px";两者等价。 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>
The above is the complete introduction to dynamically adding given data to the created table (source code). The content of this article is compact. I hope everyone can gain something. Please pay attention to the PHP Chinese website for more.
The above is the detailed content of Dynamically add the given data to the created table (source code). For more information, please follow other related articles on the PHP Chinese website!