我有几个结构相似的 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"> </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-table 类的表并检索 CA R(thead 最后一行的最后一个单元格)并使用 tbody 内的 th 和 td 创建关联数组,除了最终的“总行” “(例如:Fours => 10268.61、Hifi => 11575.91、Magneto => 11575.91)。
我的最终目标是创建一个像这样的数组:
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 ) {
});
我不知道如何从当前循环中的表格转到获取它的行和单元格。
任何帮助将不胜感激。
最佳答案
这样的事情应该有效:
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 },
...
]
关于jquery - 使用 jQuery 遍历多个 html 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15367544/