编程语言
首页 > 编程语言> > javascript-无法立即识别同一部分Google饼图的选择

javascript-无法立即识别同一部分Google饼图的选择

作者:互联网

选择特定的Google饼图切片时,我试图显示具有某些信息的模态.当一个接一个地选择不同的切片时,代码运行良好,但是第二次连续选择相同的切片时,不会触发事件.

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

解决方法:

事件被触发,但是第二次单击切片时,未选择该事件.

您应先检查所选内容的长度,然后再尝试访问-> [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>

标签:charts,pie-chart,google-visualization,javascript
来源: https://codeday.me/bug/20191118/2029314.html