Google图表HTML工具提示,其中包含javascript onclick事件

Google Charts HTML tooltip with javascript onclick event inside of it?

本文关键字:包含 javascript onclick 事件 图表 HTML 工具提示 Google      更新时间:2023-09-26

我一直在尝试在谷歌图表工具提示中使用图表选项isHtml: true进行点击事件。到目前为止,我已经尝试了两种方法来完成这项工作,但都没有成功。

1) 通过在工具提示中添加一个按钮来编写onclick函数。但是,每当我点击按钮时,我都会收到以下错误"未捕获引用-函数未定义"。我试着在指令中几乎所有地方都放置函数,但代码似乎没有接受。

工具提示中的HTML代码:

'<h5 style="padding-left:.66em;" id="export" href="#" onclick="exportCSV()">Export CSV</h5>

exportCSV函数:

var exportCSV = function(){
    console.log("Function Triggered");
}

2) 在谷歌图表中添加chart.setAction()。但这里的问题是,我在图表选项中有isHtml: True。当我尝试使用以下代码时,它似乎没有任何作用。

chart.setAction({ id: 'export', text: 'Export CSV', action: function() { selection = chart.getSelection(); console.log(selection); } });

但是,当我尝试用chart.setAction中的enabled替换函数action时,当我单击列或条形图而不是工具提示中的导出数据按钮时,代码会返回对象。

我只需要在工具提示中捕捉单击事件。如果有人能在这个问题上帮我,那就太好了。

谢谢!

I认为您只需要在全局范围内定义exportCSV
请参阅以下示例。。。

此外,如果图表options中没有tooltip {trigger: 'selection'}
我似乎无法在工具提示消失之前单击它
必须单击饼图才能查看工具提示。。。

google.charts.load('current', {
  callback: function () {
    var data = google.visualization.arrayToDataTable([
      ['Genre', 'Percentage of my books', {role: 'tooltip', type: 'string', p: {html:true}}],
      ['Science Fiction', 217, '<h5 style="padding-left:.66em;" id="export" href="#" onclick="exportCSV()">Export CSV</h5>'],
      ['General Science', 203, '<h5 style="padding-left:.66em;" id="export" href="#" onclick="exportCSV()">Export CSV</h5>'],
      ['Computer Science', 175, '<h5 style="padding-left:.66em;" id="export" href="#" onclick="exportCSV()">Export CSV</h5>'],
      ['History', 155, '<h5 style="padding-left:.66em;" id="export" href="#" onclick="exportCSV()">Export CSV</h5>'],
      ['Economics/Political Science', 98, '<h5 style="padding-left:.66em;" id="export" href="#" onclick="exportCSV()">Export CSV</h5>'],
      ['General Fiction', 72, '<h5 style="padding-left:.66em;" id="export" href="#" onclick="exportCSV()">Export CSV</h5>'],
      ['Fantasy', 51, '<h5 style="padding-left:.66em;" id="export" href="#" onclick="exportCSV()">Export CSV</h5>'],
      ['Law', 29, '<h5 style="padding-left:.66em;" id="export" href="#" onclick="exportCSV()">Export CSV</h5>']
    ]);
    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
    var options = {
      height: 400,
      tooltip: {
        isHtml: true,
        trigger: 'selection'
      },
      width: 600
    };
    chart.draw(data, options);
  },
  packages: ['corechart']
});
var exportCSV = function(){
  alert("Function Triggered");
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>