2013-03-12 97 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