谷歌图表 - 绘制后运行功能

时间:2016-09-27 08:32:36

标签: javascript jquery google-visualization asynccallback

使用谷歌图表,尝试在完成绘图后从图表中获取值,我知道我需要创建一个将在'draw'完成后运行的回调函数 - 但我无法让它工作... 我在哪里调用函数“afterDraw”使其在“draw”函数完成后运行? 请帮忙.. 谢谢:))

google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addColumn('number', 'Stam');
data.addRows([
  ['Mushrooms', 3,5],
  ['Onions', 1,7],
  ['Olives', 1,3],
  ['Zucchini', 1,5],
  ['Pepperoni', 2,8]
]);

var options = {'title':'How Much Pizza I Ate Last Night',
               'height':500};

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

}
function afterDraw(){
    alert('all done');
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<div id="chart_div"></div>

1 个答案:

答案 0 :(得分:2)

创建图表后

之前

'ready'事件

添加一个侦听器

这将告诉您何时绘制图表

google.visualization.events.addListener(chart, 'ready', afterDraw);

请参阅以下工作代码段...

google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addColumn('number', 'Stam');
data.addRows([
  ['Mushrooms', 3,5],
  ['Onions', 1,7],
  ['Olives', 1,3],
  ['Zucchini', 1,5],
  ['Pepperoni', 2,8]
]);

var options = {'title':'How Much Pizza I Ate Last Night',
               'height':500};

var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));

google.visualization.events.addListener(chart, 'ready', afterDraw);

chart.draw(data, options);

}
function afterDraw(){
    console.log('all done');
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<div id="chart_div"></div>