无法从事件处理程序中获取特定图表,因此您必须使用另一种将图表传递给处理程序的方法。这是您可以做到的一种方法:
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
函数中的特定图表。