7

如何仅在使用 javascript/jquery 的点击事件上绘制 Google 饼图?
我尝试在 onclick 事件上调用 drawChart,但没有成功。

从api:

<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Task', 'Hours per Day'],
          ['Work',     11],
          ['Eat',      2],
          ['Commute',  2],
          ['Watch TV', 2],
          ['Sleep',    7]
        ]);

        var options = {
          title: 'My Daily Activities'
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="piechart" style="width: 900px; height: 500px;"></div>
  </body>
</html>
4

2 回答 2

12

要扩展 davidkonrad 的答案,您应该将 click 事件包装在 API 加载器的回调中,因为与 Google 服务器的连接速度较慢的用户可能会在 API 完成加载之前单击绘图按钮:

function drawChart() {
    var data = google.visualization.arrayToDataTable([
        ['Task', 'Hours per Day'],
        ['Work',     11],
        ['Eat',      2],
        ['Commute',  2],
        ['Watch TV', 2],
        ['Sleep',    7]
    ]);

    var options = {
        title: 'My Daily Activities'
    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));
    chart.draw(data, options);
}
function initialize () {
    $(/* click event element selector */).click(function() {
        drawChart();
    });
}
google.setOnLoadCallback(initialize);
google.load("visualization", "1", {packages:["corechart"]});
于 2013-08-18T15:52:33.893 回答
6

只需将调用包装drawchart到点击处理程序中,而不是OnLoadCallback

  $('html, body').click(function() {
    drawChart();
  });

整个脚本:

<script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Task', 'Hours per Day'],
          ['Work',     11],
          ['Eat',      2],
          ['Commute',  2],
          ['Watch TV', 2],
          ['Sleep',    7]
        ]);

        var options = {
          title: 'My Daily Activities'
        };

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

      $('html, body').click(function() {
        drawChart();
      });

    </script>
于 2013-08-18T15:06:00.583 回答