在javascript中将html表转换为数组

问题描述:

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

How can an HTML table be converted into a JavaScript array?

<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>

这是一个可以做你想做的事的例子.

Here's one example of doing what you want.

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 创建一个键值对.

You could probably expand on this, say, using the text of the TH to instead create a key-value pair for each TD.

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

Since this implementation uses a multidimensional array, you can access a row and a td by doing something like this:

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

这是您的示例的小提琴:http://jsfiddle.net/PKB9j/1/

Here's a fiddle for your example: http://jsfiddle.net/PKB9j/1/