获取表格列的总和并添加到谷歌图表

时间:2014-02-13 10:30:25

标签: javascript jquery google-visualization

我需要从多个(5)表中获取一列的总和,并将这些总和添加到谷歌饼图中的5个实例。 我认为我的代码非常接近,但我无法解决我出错的地方。

function drawChart() {

      // calculate the sum of each table
      function sum($inputs) {
        var sum=0;
        //iterate through each input and add to sum
        $inputs.each(function() {     
                sum += parseInt($(this).text());                      
        });         

        var data = google.visualization.arrayToDataTable([
          ['Type', 'Cost'],
          ['Expense',     sum($('#expenses .amount'))],
          ['Savings',      sum($('#savings.amount'))],
          ['Commute',  2],
          ['Watch TV', 2],
          ['Sleep',    7]
        ]);

        var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
        chart.draw(data, options);
      }
    }

2 个答案:

答案 0 :(得分:1)

您需要在函数sum中返回sum值。

function drawChart() {

  // calculate the sum of each table
  function sum($inputs) {
    var sum=0;
    //iterate through each input and add to sum
    $inputs.each(function() {     
            sum += parseInt($(this).text());                      
    });
    return sum;
 }         

    var data = google.visualization.arrayToDataTable([
      ['Type', 'Cost'],
      ['Expense',     sum($('#expenses .amount'))],
      ['Savings',      sum($('#savings.amount'))],
      ['Commute',  2],
      ['Watch TV', 2],
      ['Sleep',    7]
    ]);

    var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
    chart.draw(data, options);

}

答案 1 :(得分:1)

尝试以下方法:

 function drawChart() {

  // calculate the sum of each table
  function sum($inputs) {
    var sum=0;
    //iterate through each input and add to sum
    $inputs.each(function() {     
            sum += parseInt($(this).text());                      
    });         
    return sum;
  }
    var data = google.visualization.arrayToDataTable([
      ['Type', 'Cost'],
      ['Expense',     sum($('#expenses .amount'))],
      ['Savings',      sum($('#savings.amount'))],
      ['Commute',  2],
      ['Watch TV', 2],
      ['Sleep',    7]
    ]);

    var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
    chart.draw(data, options);
}