javascript - 在javascript中将html表转换为数组

标签 javascript jquery html arrays html-table

如何将 HTML 表格转换为 JavaScript 数组?

<table id="cartGrid">
  <thead>
       <tr>
          <th>Item Description</th>
          <th>Qty</th>
          <th>Unit Price</th>
          <th>Ext Price</th>
       </tr>
  </thead>
<tbody>
    <tr><td>Old Lamp</td><td>1</td><td>107.00</td><td>107.00</td>
    <tr><td>Blue POst</td><td>2</td><td>7.00</td><td>14.00</td>
</tbody>
</table>

最佳答案

这是一个按照您的意愿行事的示例。

var myTableArray = [];

$("table#cartGrid tr").each(function() {
    var arrayOfThisRow = [];
    var tableData = $(this).find('td');
    if (tableData.length > 0) {
        tableData.each(function() { arrayOfThisRow.push($(this).text()); });
        myTableArray.push(arrayOfThisRow);
    }
});

alert(myTableArray);

您可能会对此进行扩展,例如,使用 TH 的文本来为每个 TD 创建一个键值对。

由于此实现使用多维数组,您可以通过执行以下操作来访问行和 td:

myTableArray[1][3] // Fourth td of the second tablerow

编辑:这是您的示例的 fiddle :http://jsfiddle.net/PKB9j/1/

关于javascript - 在javascript中将html表转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9579721/

相关文章:

javascript - 尝试启动我的 React 应用程序时出现异常错误。它说 CleanWebpackPlugin 不是构造函数

javascript - 将 HTML 元素列表转换为对象的 Javascript 列表

html - 如何在 Angular2 中实现 Google Analytics?

javascript - textarea onload 中的示例文本

javascript - JavaScript 代码无法识别 html 下拉菜单中的选项

jquery - 使用 JQUERY 停止元素的悬停效果

javascript - 停止将鼠标单击事件传播到父 div

android - Enter 事件不会在使用 Angular 的 Android 设备上触发该功能

html - 如何仅使用 <div> 标签和 Css 创建表

javascript - 来自 ng-model 的 Controller 中的未定义参数