2014-04-27 51 views
-1

我們可以通過下面的代碼的一組JSON數據轉換爲HTML表: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

我的問題是,當一些行列可以有自己的風格類。

所以我想改變一些表<th><th class='sampleStyle'>。你能不能讓我知道我該如何改變java腳本來從th中讀取相應的類並將其分配給相關的列。

然後將生成的表應該是這樣的:

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

順便說一句,你知道更好的辦法?

+0

你在哪裏得到的樣式類?他們保存在數據數組中嗎? –

+0

從頂部th –

回答

1

之前,您可以嘗試像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'); 
}); 
0
$("td:eq(0)", tr).addClass("sampleStyle"); 

附加TR

+0

我想從不要添加類到第一個td左右的類 –