javascript - 当用户单击栏时从列表中选择谷歌图表

标签 javascript google-visualization

我有一个循环来遍历数据并创建几个谷歌图表。我添加了一个 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/

相关文章:

javascript - 如何根据出现次数自定义谷歌时间线图表?

javascript - 在 Google Charts 中组织图表选项

javascript - JQuery 侧边栏在此 jsfiddle 中不起作用

javascript - 3 个颜色维度与 Google Visualization Geochart Color Scale

javascript - 带组的谷歌柱形图

javascript - 如何对包含 null 和未定义元素的数组使用分配函数?

javascript - 定位特定的谷歌图表数据集

javascript - 如何使用 <head> 中的本地回退从 CDN 加载 javascript

javascript - 如何从React Native的ReactActivity发送 Intent 数据到Javascript

javascript - 试图让一个 div 在悬停时从另一个 div 后面滑下来