【问题标题】:JSON to html STYLED tableJSON 到 html 样式表
【发布时间】:2014-06-13 00:10:26
【问题描述】:

我们可以通过以下代码将一组 JSON 数据转换为 html 表格:

$.each(data, function(key, val) {
    var tr=$('<tr></tr>');
    $.each(val, function(k, v){
        $('<td>'+v+'</td>').appendTo(tr);
    });
    tr.appendTo('#display');
});

html表格是:

<table border='1' id="display">

    <thead>
            <tr>
                <th>firstcol</th>
                <th>loc</th>
                <th>lastA</th>
                <th>mTime</th>
                <th>nTime</th>
                <th>Age</th>
                <th>ction</th>
            </tr>
        </thead>        
</table>

一个工作示例:http://jsfiddle.net/AHv6c/(来源jquery code to display json response to a html table using append

我的问题是某些行列可能有自己的样式类。

所以我想将表中的一些 &lt;th&gt; 更改为 &lt;th class='sampleStyle'&gt; 。能否请您告诉我应该如何更改 java 脚本以从 th 读取相应的类并将其分配给相关列。

那么生成的表应该是这样的:

<tr>
     <td>56036</td>
     <td class="sampleStyle">Deli</td>
     ....

顺便问一下,你知道更好的方法吗?

【问题讨论】:

  • 从哪里获得样式类?它们是否保存在数据数组中?

标签: javascript jquery html json html-table


【解决方案1】:
$("td:eq(0)", tr).addClass("sampleStyle");

在添加 tr 之前

【讨论】:

  • 我想从 获取类而不是添加类到第一个 td 左右
【解决方案2】:

你可以试试http://www.jqversion.com/#!/Mdi8Kla

$.each(data, function(key, val) {
    var tr    = $('<tr></tr>'),
        index = 0;
    $.each(val, function(k, v){
        $('<td>'+v+'</td>').addClass(
          $('th:eq(' + index + ')').attr('class')
        ).appendTo(tr);
        index++;
    });
    tr.appendTo('#display');
});

【讨论】:

    猜你喜欢
    • 2019-06-04
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 2017-07-31
    • 2011-07-19
    • 2012-03-12
    • 1970-01-01
    • 2012-11-02
    相关资源
    最近更新 更多