Multiple Instances of Google Visualizations Chart Inside Separate Divs

微笑、不失礼 提交于 2019-12-20 03:11:03

问题


I'm trying to show several Google Gauge charts in separate divs on the same screen. I also need to handle the click event on those divs (consequently the charts). I tried to do that dynamically but I had some issues. But anyway, even when I tried do this statically (which worked), I still couldn't get the chart area to be clickable. What happened is that the whole div is clickable except for the chart area.

Anyway, here's my (messy - test) code:

<div id="gaugePlaceHolder" class="gaugeWrapper"></div>
<div id="gaugePlaceHolder2" class="gaugeWrapper"></div>

document.getElementsByClassName = function (cl) {
    var retnode = [];
    var myclass = new RegExp('\\b' + cl + '\\b');
    var elem = this.getElementsByTagName('*');
    for (var i = 0; i < elem.length; i++) {
        var classes = elem[i].className;
        if (myclass.test(classes)) retnode.push(elem[i]);
    }
    return retnode;
};


  google.load('visualization', '1', {packages:['gauge']});
  google.setOnLoadCallback(function () {
      drawChart1();
      drawChart2();
  });
  function drawChart1() {
    var data = google.visualization.arrayToDataTable([
      ['Label', 'Value'],
      ['Memory', 80]
    ]);

    var options = {
      width: 400, height: 120,
      redFrom: 90, redTo: 100,
      yellowFrom:75, yellowTo: 90,
      minorTicks: 5
    };

  var chart = new google.visualization.Gauge(document.getElementById('gaugePlaceHolder'));
    chart.draw(data, options);
}

function drawChart2() {
    var data = google.visualization.arrayToDataTable([
      ['Label', 'Value'],
      ['Another', 30]
    ]);

    var options = {
        width: 400, height: 120,
        redFrom: 90, redTo: 100,
        yellowFrom: 75, yellowTo: 90,
        minorTicks: 5
    };

    var chart = new google.visualization.Gauge(document.getElementById('gaugePlaceHolder2'));
    chart.draw(data, options);
}

window.onload = function () {
    var elements = $('.gaugeWrapper');
    console.log(elements);
    elements.click(function () {
        alert("clicked");
    });
}

Any explanations/suggestions?


回答1:


The right way to add a listener to a Gauge is using google.visualization.events.addListener method, as shown in this example.

You could also try your code on Google Playground.



来源:https://stackoverflow.com/questions/10848217/multiple-instances-of-google-visualizations-chart-inside-separate-divs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!