我有一个循环来遍历数据并创建几个谷歌图表。我添加了一个 selectHandler
,它在单击图表的条形时执行某些操作。一旦有了图表,我就可以毫无问题地选择栏,但我不知道如何告诉处理程序单击了哪个图表。
这是代码:
在循环中的drawChart()
内部:
chart[chart_index] = new google.visualization.BarChart(document.getElementById('chart_div<%= qcount %>'));
chart[chart_index].draw(data, {width: 450, height: 300, title: 'title'});
google.visualization.events.addListener(chart[chart_index], 'select', selectHandler);
chart_index = chart_index+1;
selectHandler 的工作方式如下:
function selectHandler(e) {
var bar_index = chart[HERE_GOES_THE_CHART_INDEX].getSelection()[0].row;
}
谢谢
最佳答案
无法从事件处理程序获取特定图表,因此您必须使用另一种方法将图表传递给处理程序。这是一种方法:
function selectHandler(myChart) {
// test to see if anything was selected before you get the index
// otherwise you will get errors when the selection contains 0 elements
var selection = myChart.getSelection();
if (selection.length) {
var bar_index = selection[0].row;
// do something with bar_index
// you should also test bar_index, as the user could have clicked a legend item, which would give a null value for row
}
}
chart[chart_index] = new google.visualization.BarChart(document.getElementById('chart_div<%= qcount %>'));
// generally speaking, you should add event handlers before drawing the chart
google.visualization.events.addListener(chart[chart_index], 'select', (function (x) {
return function () {
selectHandler(chart[x]);
}
})(chart_index));
chart[chart_index].draw(data, {width: 450, height: 300, title: 'title'});
chart_index = chart_index+1;
此闭包将 chart_index
传递到闭包内部,并将其分配给 x
:
(function (x) {
return function () {
selectHandler(chart[x]);
}
})(chart_index)
因此,x
的值被锁定在闭包内,即使您稍后增加 Chart_index 也是如此。闭包返回一个函数,该函数成为事件处理程序。当有人单击图表元素时,此函数调用 selectHandler
,传入 chart[x]
。如果您在循环中对此进行迭代,则 x
的值在每个闭包内将是唯一的,使您能够在 selectHandler
函数中引用特定图表。
关于javascript - 当用户单击栏时从列表中选择谷歌图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19861984/