当用户点击条形图时,从列表中选择谷歌图表

Select google chart from list when user clicks on bar

本文关键字:列表 选择 谷歌 用户 条形图      更新时间:2023-09-26

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

选择处理程序的工作方式如下:

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 函数中引用特定图表。

在阅读谷歌可视化事件处理后...

选择事件:

select 事件不会将任何属性或对象传递给 处理程序(您的函数处理程序不应期望任何参数 传递给它)。

因此,尽管您可以使用 getSelection(),但您需要另一个函数来确定已对哪个图表进行操作。 输入另一个事件处理程序:

// google.visualization.table exposes a 'page' event.
google.visualization.events.addListener(table, 'page', myPageEventHandler);
...
function myPageEventHandler(e) {
  alert('The user is navigating to page ' + e['page']);
}

您需要一个在 param 中传递事件对象的事件处理程序,以便您可以确定正在发生的图表。 获得当前图表后,可以使用 getSelection() 查看该图表中的当前选择。

绑定到救援的函数。

google.visualization.events.addListener(chart[chart_index], 'select', selectHandler.bind(chart[chart_index]));

您的处理程序将始终将图表作为第一个参数接收。

如果你的目标是较旧的浏览器,这里有一个由Mozilla工作人员编写的很棒的绑定polyfill:MDN Function.prototype.bind()