我一直在尝试通过图表选项isHtml: true在Google图表工具提示中发生点击事件。到目前为止,我已经尝试了两种方法来完成此任务,但没有成功。

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)在Google图表中添加chart.setAction()。但是这里的问题是,图表选项中有isHtml: True。当我尝试使用以下代码时,它似乎没有任何作用。

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

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

我所需要的只是捕获工具提示中的click事件。如果有人可以帮助我解决这个问题,那就太好了。

谢谢!

最佳答案

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

另外,在图表tooltip {trigger: 'selection'}中没有options的情况下,
我似乎无法在工具提示消失之前单击它。
必须点击饼图以查看工具提示...



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>

07-24 19:15
查看更多