首頁  >  文章  >  web前端  >  將給定的資料動態加入到建立的表格中(原始碼)

將給定的資料動態加入到建立的表格中(原始碼)

云罗郡主
云罗郡主轉載
2018-10-18 14:12:061750瀏覽

這篇文章帶給大家的內容是關於將給定的資料動態加入到創建的表格中(原始碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。

想法:

  1. 建立table thead tbody

  2. 建立tr th

  3. 建立每一行的tr td

  4. 加到頁面中

註:最後再加到頁面中的原因是每將一個元素加到頁面一次,頁面便會刷新一次,因此先在內存中創建好表格再一次性的加到頁面中,頁面只需刷新一次,減少性能的損失。

<!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>

以上就是將給定的資料動態加入到創建的表格中(原始碼)的全部介紹,本文內容緊湊,希望大家可以有所收穫,更多請關注PHP中文網。        



#

以上是將給定的資料動態加入到建立的表格中(原始碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除