2012-09-26 78 views
0

我是jquery的新手,忙於創建基於表的圖形。我發現一個很好的例子:http://coding.smashingmagazine.com/2011/09/23/create-an-animated-bar-graph-with-html-css-and-jquery/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

它創建一個二維array [0] [0]是1,array [0] [1]是2,array [1] [0]是3,array [1] [1]是4等。此結構與表匹配佈局,你想要什麼呢? – Barmar

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