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?
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