javascript - 使用 jQuery 从表创建数组

标签 javascript jquery html

我正在寻找使用 jQuery 从带有 <thead> 的表中创建一个数组和一个 <tbody>

我要找的结果是

[[20th Jan, 33], [21st Jan, 44], [22nd Jan, 5],[23rd Jan, 17]]

我的表格如下

<table class="" id="bookedTable" border="1">
<thead>
    <tr>
        <th>Date</th>
        <th>20th jan</th>
        <th>21st jan</th>
        <th>22nd jan</th>
        <th>23rd Jan</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>Name</td>
        <td>33</td>
        <td>44</td>
        <td>5</td>
        <td>17</td>
    </tr>
</tbody>

我的JS如下

$(function() {
var $table = $("#bookedTable"),
  $headerCells = $table.find("thead th"),
  $rowCells = $table.find("tbody tr td");

var headers = [],
  rows = [];

$headerCells.each(function(k,v) {
 headers[headers.length] = $(this).text();
});

$rowCells.each(function(k,v) {
 rows[rows.length] = $(this).text();
});

console.log(headers);
console.log(rows);
});

我只能弄清楚如何分别控制台记录标题和行,而不是根据上面我想要的结果将它们组合在 1 个数组中。寻求一些帮助来解决。

MY DEMO HERE

最佳答案

var combined = [];  

for(var i = 1; i < $headerCells.length; i++) {
    combined.push([$($headerCells[i]).text(), $($rowCells[i]).text()]);
}

看这里:

http://jsfiddle.net/kp7zK/2/

关于javascript - 使用 jQuery 从表创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21234505/

相关文章:

Jquery 灯箱点击 :not

jquery - 将显示设置为可见时表单元素的垂直对齐方式跳跃

html - float 而不覆盖填充

javascript - 通过 Express 发送静态资源时,如何在开发过程中自动刷新浏览器?

javascript - 如何获取延迟加载加载的图像的图像大小

javascript - 如何改变事件的顺序?

javascript - 服务器端javascript的主要优点是什么?

jQuery Mobile URL 未更新

javascript - ionic 形式的键盘事件

javascript - 仅在页面大小更改时重新加载网页