jQuery从表中选择值

时间:2012-09-26 09:52:16

标签: jquery html-table

我是jQuery的新手,忙着根据表格创建图表。我找到了一个很好的例子:http://coding.smashingmagazine.com/2011/09/23/create-an-animated-bar-graph-with-html-css-and-jquery/

但我的问题是如何选择一个表并将它们放在一个数组中?

    <table id="data-table" border="1" cellpadding="10" cellspacing="0">
      <caption>
        table
      </caption>
      <thead>
        <tr>
          <td>month</td>
          <th scope="col">usage 1</th>
          <th scope="col">usage 2</th>

        </tr>
      </thead>
      <tbody>
        <tr>
          <th scope="row">jan</th>
          <td>1</td>
          <td>2</td>
        </tr>
        <tr>
          <th scope="row">feb</th>
          <td>3</td>
          <td>4</td>
        </tr>
        <tr>
          <th scope="row">march</th>
          <td>5</td>
          <td>6</td>
        </tr>
                    <tr>
          <th scope="row">april</th>
          <td>7</td>
          <td>8</td>
        </tr>
                    <tr>
          <th scope="row">may</th>
          <td>9</td>
          <td>10</td>
        </tr>
      </tbody>
    </table>

如果我正在查看教程,我会看到它从左到右选择并将它们放在两个数组中。

    // Sort data into groups based on number of columns
    columnGroups: function() {
     var columnGroups = [];
   // Get number of columns from first row of table body
   var columns = data.find('tbody tr:eq(0) td').length;
   for (var i = 0; i < columns; i++) {
      columnGroups[i] = [];
      data.find('tbody tr').each(function() {
         columnGroups[i].push($(this).find('td').eq(i).text());
      });
   }
   return columnGroups;
}

如何进入5个数组,值为1,2而不是1,3,5,7,9,

1 个答案:

答案 0 :(得分:0)

$(function(){
   var columnGroups = [],
       table = $('#data-table');

  table.find('tbody tr').each(function(index) {
     columnGroups[index] = [];
     $(this).find('td').each(function() {
         columnGroups[index].push($(this).text());
     });
  });

  console.log(columnGroups);
});

演示:http://jsfiddle.net/tdmvt/