Google Chart BarChart鼠标悬停

时间:2018-08-08 13:37:04

标签: charts google-visualization bar-chart onmouseover

我正在尝试在Google BarChart的“ onmouseover”事件上添加侦听器,但无法使其正常工作。我想使用“ mouseover”元素进行ajax调用...(我的代码的一部分):

dataTable = google.visualization.arrayToDataTable(dataRaw, false); 
            var chart = new google.visualization.BarChart(document.getElementById("successChart"));

            //Setting options for the chart
            var options = {}....;

            chart.draw(dataTable, options);
            // Add actionlistener
            google.visualization.events.addListener(chart, 'select', selectHandler);
            google.visualization.events.addListener(chart, 'onmouseover', onmouseoverHandler);

 function onmouseoverHandler() {

                var selectedItem = chartGennemført.getSelection()[0]; // gets the value the vAxis
            }

“选择”处理程序工作正常(代码中未显示),但“ onmouseover”无效。如何添加onmouseoverHandler ...任何建议?

1 个答案:

答案 0 :(得分:0)

事件监听器需要添加到图表中在绘制之前

此外,'onmouseover'事件还将行和列作为参数传递给侦听器函数

并且getSelection返回一个数组,当选择和未选择图表元素时,
在尝试访问内容之前,需要检查数组的长度...

如果未选择

,则会失败
getSelection()[0]

请参阅以下工作片段...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var dataRaw = [
    ['x', 'y'],
    [0, 0],
    [1, 1],
    [2, 2],
    [3, 3],
    [4, 4],
    [5, 5]
  ];

  dataTable = google.visualization.arrayToDataTable(dataRaw, false);
  var chart = new google.visualization.BarChart(document.getElementById("successChart"));

  var options = {};

  // Add actionlistener
  google.visualization.events.addListener(chart, 'select', selectHandler);
  google.visualization.events.addListener(chart, 'onmouseover', onmouseoverHandler);

  chart.draw(dataTable, options);

  function onmouseoverHandler(properties) {
    console.log(JSON.stringify(properties));
  }

  function selectHandler() {
    var selectedItem = chart.getSelection();
    if (selectedItem.length > 0) {
      console.log(JSON.stringify(selectedItem[0]));
    } else {
      console.log('nothing selected');
    }
  }
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="successChart"></div>