如何为谷歌图表设置事件

How to set event for Google chart?

本文关键字:设置 事件 谷歌      更新时间:2023-09-26

嗨,我正在使用Google API绘制图表但是我想为表格的每一行设置事件但是我不知道该如何收集这个元素例如,我想设置事件每当点击Magnolia Room alert("Magnolia Room clicked");
Google图表链接:
谷歌时间图
以下是Google javascript图表代码:

 <script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization',
       'version':'1','packages':['timeline']}]}"></script>
    <script type="text/javascript">
        google.setOnLoadCallback(drawChart);
        function drawChart() {
            var container = document.getElementById('example5.3');
            var chart = new google.visualization.Timeline(container);
            var dataTable = new google.visualization.DataTable();
            dataTable.addColumn({ type: 'string', id: 'Room' });
            dataTable.addColumn({ type: 'string', id: 'Name' });
            dataTable.addColumn({ type: 'date', id: 'Start' });
            dataTable.addColumn({ type: 'date', id: 'End' });
            dataTable.addRows([
                [ 'Magnolia Room',  'CSS Fundamentals',    new Date(0,0,0,12,0,0),  new Date(0,0,0,14,0,0) ],
                [ 'Magnolia Room',  'Intro JavaScript',    new Date(0,0,0,14,30,0), new Date(0,0,0,16,0,0) ],
                [ 'Magnolia Room',  'Advanced JavaScript', new Date(0,0,0,16,30,0), new Date(0,0,0,19,0,0) ],
                [ 'Gladiolus Room', 'Intermediate Perl',   new Date(0,0,0,12,30,0), new Date(0,0,0,14,0,0) ],
                [ 'Gladiolus Room', 'Advanced Perl',       new Date(0,0,0,14,30,0), new Date(0,0,0,16,0,0) ],
                [ 'Gladiolus Room', 'Applied Perl',        new Date(0,0,0,16,30,0), new Date(0,0,0,18,0,0) ],
                [ 'Petunia Room',   'Google Charts',       new Date(0,0,0,12,30,0), new Date(0,0,0,14,0,0) ],
                [ 'Petunia Room',   'Closure',             new Date(0,0,0,14,30,0), new Date(0,0,0,16,0,0) ],
                [ 'Petunia Room',   'App Engine',          new Date(0,0,0,21,30,0), new Date(0,0,1,0,30,0) ]]);
            var options = {
                timeline: { colorByRowLabel: true },
                backgroundColor: '#ffd'
            };
        chart.draw(dataTable, options);
    }
</script>

And My HTML:

<!DOCTYPE html>
<html>
  <head>
     <title>sample</title>
  </head>
  <body>
     <div id="example5.3" style="width: 900px; height: 200px;"></div>
  </body>
</html>

是否有办法为他们设置一个事件?

您可以使用"select"事件处理程序来完成此操作:

google.visualization.events.addListener(chart, 'select', function () {
    var selection = chart.getSelection();
    if (selection.length) {
        alert(dataTable.getValue(selection[0].bb, 0) + ' clicked');
    }
});

请注意,选择信息目前是错误的;选择对象应该有rowcolumn属性,但是这些属性是模糊的,所以现在你必须从bb属性访问行索引。Timeline可视化将所有选择的列索引设置为null,因此您无需担心这一点。