簡體   English   中英

用來自JavaScript數組的數據創建HTML表的最快方法是什么?

[英]What is the fastest way to create HTML table with data from JavaScript array?

我有以下代碼將JSON數據集轉換為html表。 我想知道這是否是最快的方法,還是應該將jqote2與jquery一起使用來編寫模板?

要求:

  • 單擊即可更改col定義(客戶端可以更改查看表的方式,col定義數組將更改,並且表可以重建)
  • 排序,過濾器和分頁(我相信可以對原始數據進行排序並可以重建表)
  • 轉換(如果說1個col包含以不同單位表示長度的數據,則可以在原始數據集中添加新的col以1個相同單位顯示數據,以便可以對數據進行排序)

因此,如果我在正確的軌道上工作或正在從事已經存在的工作,有人可以指導我嗎?

<div id="hii"><!-- table loads here --></div>

<script>
var set1={ // JSON dataset & col definitions
    'col':[ // definition/template of data to load in column cells
        [function(x){return '<a href="?sid='+x[1]+'">'+x[0]+'</a>';}],
        [function(x){return '<a href="?id='+x[2]+'">'+x[2]+'</a>';}],
    ],
    'data':[ // raw data, output table has only 2cells/row using these 3 values from each row
        ['Name 1','00000001','Value 1'],
        ['Name 2','00000002','Value 2'],
        ['Name 3','00000003','Value 3'],
        ['Name 4','00000004','Value 4'],
        ['Name 1','00000001','Value 5'],
        ['Name 5','00000005','Value 1'],
        ['Name 6','00000006','Value 1'],
        ['Name 7','00000007','Value 2'],
        ['Name 8','00000008','Value 6'],
        ['Name 9','00000009','Value 3'],
        ['Name A','00000010','Value 7'],
        ['Name B','00000011','Value 7'],
        ['Name C','00000012','Value 1'],
    ],
};
function tbody(x){ // function to create table, using dataset name passed to x
    for(i=0,data='';i<x.data.length;i++){
        data+='<tr>';
        for(j=0;j<x.col.length;j++){
            data+='<td>'+x.col[j][0](x.data[i])+'</td>';
        }
        data+='</tr>';
    }
    return data;
}
document.getElementById('hii').innerHTML='<table>'+tbody(set1)+'</table>';
</script>

您可以使用Datatables 它可以與jQuery一起使用,也可以使用。 您可以設置很多選項來滿足您的要求,甚至更多。

jquery / jqote也可以做到這一點:

$('#container tbody').empty().html($('#row_template').jqote(set1));

<script type="text/x-jqote-template" id="row_template">
<![CDATA[
    <tr id="<%=this.id%>_valuebox">
        <td><%=this.name%></td>
        <td><%=this.value%></td>
    </tr>
]]>
</script>

這並非易事。 看一下Sencha(extJS),尤其是網格-http: //www.sencha.com/learn/legacy/Tutorials,http : //www.sencha.com/learn/legacy/Tutorials#Grids

看一下jQuery模板插件。

http://api.jquery.com/category/plugins/templates/

<ul id="movieList"></ul>

<script id="movieTemplate" type="text/x-jquery-tmpl">
    <li><b>${Name}</b> (${ReleaseYear})</li>
</script>

<script type="text/javascript">
    var movies = [
        { Name: "The Red Violin", ReleaseYear: "1998" },
        { Name: "Eyes Wide Shut", ReleaseYear: "1999" },
        { Name: "The Inheritance", ReleaseYear: "1976" }
    ];

    // Render the template with the movies data and insert
    // the rendered HTML under the "movieList" element
    $( "#movieTemplate" ).tmpl( movies )
        .appendTo( "#movieList" );
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM