通过jQuery将HTML表数据转换为数组

sov*_*ova 8 javascript jquery highcharts

我想从像html表中提取数据

<table>
    <tr>
        <th> Header1 </th>
        <th> Header2 </th>
        <th> Header3 </th>
    </tr>
    <tr>
        <td> Value 1,1 </td>
        <td> Value 2,1 </td>
        <td> Value 3,1 </td>
    </tr>

    ... rows ...

</table>
Run Code Online (Sandbox Code Playgroud)

并获取数组:

  • 标题的数组
  • 列值的二维数组(或每列的数组)

    我怎么能用jQuery做到这一点?

    我不关心它序列化,或者把它放到JSON对象中因为我想用它来渲染图表.


    相关的一般设计问题:

    此刻我有类似的东西

    1. ajax query returns html table
    2. use jQuery to get values from html table
    3. render chart
    
    Run Code Online (Sandbox Code Playgroud)

    从ajax查询中抛出JSON对象然后从那里渲染表和图表会更有意义吗?

  • sim*_*aun 14

    像这样的东西?

    $(function() {
    
      var headers = $("span",$("#tblVersions")).map(function() { 
        return this.innerHTML;
      }).get();
    
      var rows = $("tbody tr",$("#tblVersions")).map(function() { 
        return [$("td:eq(0) input:checkbox:checked",this).map(function() { 
          return this.innerHTML;     
        }).get()];
      }).get();
    
      alert(rows);
    });
    
    Run Code Online (Sandbox Code Playgroud)


    Ish*_*Ish 9

    演示更新http://jsfiddle.net/ish1301/cnsnk/

    var header = Array();
    
    $("table tr th").each(function(i, v){
            header[i] = $(this).text();
    })
    
    alert(header);
    
    var data = Array();
    
    $("table tr").each(function(i, v){
        data[i] = Array();
        $(this).children('td').each(function(ii, vv){
            data[i][ii] = $(this).text();
        }); 
    })
    
    alert(data);
    
    Run Code Online (Sandbox Code Playgroud)