如何为Google图表设置活动?

时间:2014-07-19 11:13:26

标签: javascript jquery charts google-visualization

您好我正在使用Google API绘制图表,但我想为此表的每一行设置事件但我不知道应该如何收集此元素,例如我想设置每次点击 Magnolia时的事件房间 alert("Magnolia Room clicked");
谷歌图表链接:
Google Timeline Chart
这是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>

我的HTML:

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

有没有办法为他们设置事件?

1 个答案:

答案 0 :(得分:0)

您可以使用&#34;选择&#34;事件处理程序:

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

请注意,选择信息目前存在漏洞;选择对象应具有rowcolumn属性,但这些属性是混淆的,因此现在您必须从bb属性访问行索引。对于所有选择,时间轴可视化将列索引设置为null,因此您不必担心该列索引。