当用户点击条形图时,从列表中选择谷歌图表
Select google chart from list when user clicks on bar
我有一个循环,可以遍历数据并创建几个谷歌图表。 我添加了一个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()
- Angular:使用选择列表选择过滤代码中的对象
- JavaScript类列表选择器错误
- 将下拉列表“选择值”传递到 URL
- 禁用基于下拉列表选择 asp.net JavaScript 启用文本框
- 下拉列表<选择>为列表.js
- 经典 ASP - 下拉列表:选择与第一个下拉列表具有相同值的所有下拉列表
- 映射下拉列表选择到URL
- 删除基于先前下拉列表选择的“选择下拉列表”选项
- 在下拉列表选择中显示模态
- 下拉列表选择的值在UI淘汰js中没有更新
- 如何将 ID 分配给动态下拉列表选择
- 使用 dojo 将鼠标悬停在动态下拉列表选择上时添加工具提示
- 链接下拉列表选择列表代码 -- 连接数据
- Javascript 不遵循下拉列表选择
- 检索引导下拉列表选择文本
- 表单事件更改不适用于下拉列表选择
- 无法检测加载时的选择/下拉列表选择事件
- 将 CakePHP 命名参数添加到列表选择的 URL 中
- 为什么聚合物核心列表选择中的切换操作不正确
- 为列表选择类并仅设置其中一个类