立即选择相同的谷歌饼图未被识别

时间:2016-05-31 12:10:03

标签: javascript charts google-visualization pie-chart

当我选择特定的谷歌饼图时,我试图显示具有某些信息的模态。当一个接一个地选择不同的切片但是当第二次连续选择相同切片时没有触发事件时,代码工作正常。

google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler()
                    {
                        var selectedItem = chart.getSelection()[0];
                        if (selectedItem)
                        {
                            alert("here");
                        }
                    }

1 个答案:

答案 0 :(得分:3)

事件触发但第二次点击切片时, un - 已选中。

在尝试访问之前,您应该检查选择的长度 - > [0]

参见以下示例......



google.charts.load('current', {
  callback: function () {
    var data = google.visualization.arrayToDataTable([
      ['Task', 'Hours per Day'],
      ['Work',     12],
      ['Eat',       2],
      ['Drink',     1],
      ['Commute',   1],
      ['Surf',      1],
      ['Watch TV',  1],
      ['Sleep',     6]
    ]);

    var pieChart = new google.visualization.PieChart(document.getElementById('piechart'));
    google.visualization.events.addListener(pieChart, 'select', function () {
      document.getElementById('selection').innerHTML = 'Items selected: ' + pieChart.getSelection().length;
    });
    pieChart.draw(data, {});
  },
  packages: ['corechart']
});

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="piechart"></div>
<div id="selection"></div>
&#13;
&#13;
&#13;