如何将 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/