到目前为止,我们所讨论的内容对于许多web页面来说已经足够了:您已经在页面上绘制了图表。但是,如果您想捕获用户单击,或者需要在已经绘制的图表中操作属性或数据,则需要侦听图表引发的事件。
所有图表都会抛出一些事件。以下是最常见的:
倾听事件很简单;只需调用google. visualiz.events . addListener(),将句柄传递给图表、要捕获的事件的名称以及抛出事件时要调用的处理程序的名称。您可以使用任何图表句柄调用此方法,即使您还没有调用draw()。注意,如果希望在删除侦听器之前只调用一次侦听器,可以调用google.visualization.events.addOneTimeListener()
。
下面是部分代码片段,展示了如何注册以捕获图表的select事件:
load libraries...
function drawChart() {
prepare data...
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
// The select handler. Call the chart's getSelection() method
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
var value = data.getValue(selectedItem.row, selectedItem.column);
alert('The user selected ' + value);
}
}
// Listen for the 'select' event, and call my function selectHandler() when
// the user selects something on the chart.
google.visualization.events.addListener(chart, 'select', selectHandler);
draw the chart...
}
下面显示了Hello Charts代码示例,其中包含一个新的select事件侦听器。你自己试试吧。
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
function selectHandler() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
var topping = data.getValue(selectedItem.row, 0);
alert('The user selected ' + topping);
}
}
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div" style="width:400; height:300"></div>
</body>
</html>