将JavaScript链接添加到google visualizations饼图的饼图部分
我正在制作一个谷歌可视化饼图,希望每个单独的部分链接到不同的页面。我知道还有一个问题与此非常相似,但我不明白答案。我曾经使用过HTML和CSS,但这是我用JavaScript做的第一件事,我肯定是迷路了。我希望我的用户能够单击图表的某个部分,然后进入新页面。如果可能,图表的每个部分的页面都需要不同。非常感谢。 这是我的密码:将JavaScript链接添加到google visualizations饼图的饼图部分,javascript,charts,google-visualization,pie-chart,google-pie-chart,Javascript,Charts,Google Visualization,Pie Chart,Google Pie Chart,我正在制作一个谷歌可视化饼图,希望每个单独的部分链接到不同的页面。我知道还有一个问题与此非常相似,但我不明白答案。我曾经使用过HTML和CSS,但这是我用JavaScript做的第一件事,我肯定是迷路了。我希望我的用户能够单击图表的某个部分,然后进入新页面。如果可能,图表的每个部分的页面都需要不同。非常感谢。 这是我的密码: <html> <head> <html> <head> <script type="text/java
<html>
<head>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Field', 'Number of Proposals'],
['Sustainability', 242],
['Education', 699],
['Information Technology', 240],
['Health & Wellness', 247],
['Community Development', 353],
['Public Policy', 138],
['Equity', 276],
['Food & Water', 131],
['Energy', 84],
['Security (Cyber & Other)', 56],
]);
var options = {'width': 1200,
'height': 700,
colors: ['#8C1D40', '#FFC627', '#6F6F6F', '#935669', '#FFDA74', '#919191', '#96757F', '#FEE9B0', '#BBBBBB', '#DEDEDE']
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
google.visualization.events.addListener (chart, 'select', function(){
var selection = chart.getSelection();
console.log(selection);
});
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
首先,应该在绘制图表之前添加图表事件
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
google.visualization.events.addListener(chart, 'select', function() {
...
});
chart.draw(data, options);
接下来,“选择”事件在选择一个切片时触发,单击。
再次单击时取消选择。
所以我们必须检查选择的长度,
在尝试访问所选内容之前
var selection = chart.getSelection();
if (selection.length > 0) { // <-- check length of the selection
}
然后在select事件中,我们可以从选择中获取属性并打开页面
var url = data.getProperty(selection[0].row, 0, 'url');
window.open(url, '_blank'); // <-- remove '_blank' to open the page in the same window
希望这能有所帮助-注意:图表是使用绘制的,而不是-这就是为什么我们需要使用图表事件来侦听选择-我们不能只向
var url = data.getProperty(selection[0].row, 0, 'url');
window.open(url, '_blank'); // <-- remove '_blank' to open the page in the same window