在javascript中将html表转换为数组 [英] Convert html table to array in javascript

查看:38
本文介绍了在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/

这篇关于在javascript中将html表转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆