2013-03-12 111 views
2

我有幾個結構相似的HTML表格。他們倆是這個樣子:使用jQuery遍歷多個html表格

<table cellspacing="1" cellpadding="7" summary="Procedure Tabulate: Table 1" frame="box" rules="groups" class="table table-bordered table-hover highchart-table"> 
    <thead> 
     <tr> 
      <th scope="col" rowspan="2" class="c m Header">&nbsp;</th> 
      <th scope="col" class="c Header">3</th> 
     </tr> 
     <tr> 
      <th scope="col" class="c Header">CA R</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
      <th scope="row" class="l t RowHeader">Fours</th> 
      <td class="r b Data">10268.64</td> 
     </tr> 
     <tr> 
      <th scope="row" class="l t RowHeader">Hifi</th> 
      <td class="r b Data">11267.82</td> 
     </tr> 
     <tr> 
      <th scope="row" class="l t RowHeader">Magneto</th> 
      <td class="r b Data">11575.91</td> 
     </tr> 
     <tr class="blue-bg"> 
      <th scope="row" class="l t RowHeader">Total</th> 
      <td class="r b Data">33112.36</td> 
     </tr> 
    </tbody> 
</table> 

我想通過一類highchart表的所有表與次運行和檢索CA R(THEAD的最後一行的最後一個單元格),並創建關聯數組並且除了最終的「總線」(例如:Fours => 10268.61,Hifi => 11575.91,Magneto => 11575.91)之外的tbody內。

我的最終目標是創建一個數組是這樣的:

hcArr[0]['ind'] = 'CA R'; 
hcArr[0]['Fours'] = 10268.61; 
hcArr[0]['Hifi'] = 11575.91; 
hcArr[0]['Magneto'] = 11575.91; 

再有hcArr[1]其中包含的下一個表的內容與類的highchart-table

目前我已經是工作的唯一代碼:

$.each($('.highchart-table'), function(key, value) { 

}); 

我無法弄清楚如何再從具有電流回路表,以獲取它的行和單元格去。

任何幫助將不勝感激。

回答

1

像這樣的東西應該工作:

var res = []; 

$(".highchart-table").each(function() { 
    var $$ = $(this), obj = {}; 
    obj.ind = $(this).find('thead tr:last th:last').text(); 
    $$.find("tbody th").each(function(){ 
    obj[$(this).text()] = parseFloat($(this).siblings("td").text()); 
    }); 
    res.push(obj); 
}); 

console.log(res); 

順便提一下,在javascript數組只有數字索引,所以它會返回一個對象數組是這樣的:

[ 
    { "ind": "CA R", "Fours": 10268.64, "Hifi": 11267.82, "Magneto": 11575.91 }, 
    { "ind": "CA R", "Fours": 10268.64, "Hifi": 11267.82, "Magneto": 11575.91 }, 
    ... 
] 
+0

感謝@Nabab,這段代碼工作正常。 – xonorageous 2013-03-13 07:25:58

1

這不是最終的解決方案,但是這會爲您提供標題單元格中的初始值。你可以從中推斷出其他人。 http://jsfiddle.net/tM546/

var theadValues = $.map($('.highchart-table'), function (idx, el) { 
    return $(idx).find('thead tr:last th:last').text(); 
}); 
+0

謝謝,我忘了使用.map,我只是在考慮使用標準的foreach循環 – xonorageous 2013-03-12 17:11:13

+0

@xonorageous沒有問題:) – 2013-03-12 17:13:01