jquery - 使用 jQuery 遍历多个 html 表

标签 jquery html arrays html-table

我有几个结构相似的 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-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/

相关文章:

php - Ajax 将格式化文本传递到另一个 php 文件并显示在文本区域中

javascript - JQuery工具,从输入框溢出图像

python - 使用 Flask 检索非输入字段的值

javascript - 滚动 safari bug 上元素的增长高度

java - JNI 访问数组的数组

Java 2d 数组正在打印我认为内存中的垃圾而不是元素

c++ - 我在 C++ 数组初始化方面遇到了麻烦

javascript - 如何获取未包含在任何html标签中的innertext

javascript - 如何在搜索过滤后选择 jQuery Chosen 多选中的所有选项?

html - Bootstrap面板定位