2

我正在使用谷歌时间线图。是否可以通过将第一列设为 html 来使其可点击?

我尝试使列(用户名)允许 html,这样当我尝试添加行时,我可以将其作为这样的链接<a href="http://www.google.com">Google</a>

dataTable.addColumn({type: 'string', id: 'User Name', p: {html: true}});
dataTable.addColumn({type: 'string', id: 'User Id'});
dataTable.addColumn({type: 'string', role: 'tooltip', p: {html: true}});
dataTable.addColumn({type: 'string', id: 'style', role: 'style'});
dataTable.addColumn({type: 'date', id: 'Start'});
dataTable.addColumn({type: 'date', id: 'End'});

但这似乎不起作用,它被呈现为纯文本。

4

1 回答 1

2

图表没有提供任何点击事件
, 但我们可以使用 javascript/jquery 添加常规事件。

'ready'我们只需要在分配事件监听器之前 等待图表的事件。

google.visualization.events.addListener(chart, 'ready', function () {
  $(chart.getContainer()).find('text[text-anchor="end"]').on('click', onLabelClick);
});

在这里,我们使用<text>元素过滤器[text-anchor="end"]
仅将事件分配给行标签,而不是 x 轴标签。

请参阅以下工作片段,
它使用单元格属性来存储 url,
单击时将被检索。

google.charts.load('current', {
  packages: ['timeline']
}).then(function () {
  var container = document.getElementById('timeline');
  var chart = new google.visualization.Timeline(container);
  var dataTable = new google.visualization.DataTable();
  dataTable.addColumn({type: 'string', id: 'User Name'});
  dataTable.addColumn({type: 'string', id: 'User Id'});
  dataTable.addColumn({type: 'string', role: 'tooltip', p: {html: true}});
  dataTable.addColumn({type: 'string', id: 'style', role: 'style'});
  dataTable.addColumn({type: 'date', id: 'Start'});
  dataTable.addColumn({type: 'date', id: 'End'});
  dataTable.addRows([
    [{v: 'User A', p: {url: 'https://www.google.com'}}, '1', null, 'cyan', new Date(2020, 0, 1), new Date(2020, 0, 31)],
    [{v: 'User B', p: {url: 'https://www.yahoo.com'}}, '2', null, 'magenta', new Date(2020, 1, 1), new Date(2020, 1, 14)],
    [{v: 'User C', p: {url: 'https://www.bing.com'}}, '3', null, 'lime', new Date(2020, 2, 1), new Date(2020, 2, 10)]
  ]);

  google.visualization.events.addListener(chart, 'ready', function () {
    $(chart.getContainer()).find('text[text-anchor="end"]').on('click', onLabelClick);
  });

  chart.draw(dataTable);

  function onLabelClick(sender) {
    var label = $(sender.target).text();
    var rowIndex = dataTable.getFilteredRows([{
      column: 0,
      value: label
    }])[0];
    var url = dataTable.getProperty(rowIndex, 0, 'url');
    console.log(label, url);
    // window.open(url, '_blank');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="timeline" style="height: 180px;"></div>

于 2020-02-14T23:47:02.400 回答