微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 将链接插入Google Charts API数据?

我已经在谷歌图表中玩过谷歌图表,在这里玩谷歌:

Link

我一直在玩的代码是:

function drawVisualization() {
  // Create and populate the data table.
  var data = google.visualization.arrayToDataTable([
    ['Year','Austria'],['2003',1336060],['2004',1538156],['2005',1576579],['2006',1600652],['2007',1968113],['2008',1901067]
  ]);

  // Create and draw the visualization.
  new google.visualization.BarChart(document.getElementById('visualization')).
      draw(data,{title:"Yearly Coffee Consumption by Country",width:600,height:400,vAxis: {title: "Year"},hAxis: {title: "Cups"}}
      );
}

这给了我一个很好的图表,看起来像这样:

我试图让这个图表符合我的网站的需要,为此,我需要把左边链接名称放在另一个页面上.所以例如2003年将是一个链接,用户可以点击ans,所以2004年等

我试图做这样的事情:

function drawVisualization() {
  // Create and populate the data table.
  var data = google.visualization.arrayToDataTable([
    ['Year',['<a href="url">Link text</a>',hAxis: {title: "Cups"}}
      );
}

但我只能希望它是那么容易,而不是.有人知道这是否可以吗?

解决方法

这是不平凡的,因为您看到的输出是SVG,而不是HTML.您的示例中的标签(“2004”,“2005”等)嵌入在SVG文本节点中,因此在其中插入原始HTML标记将不会呈现为HTML.

解决方法是扫描包含目标值的文本节点(再次“2004”,“2005”等),并将其替换为ForeignObject个元素. ForeignObject元素可以包含常规HTML.然后,需要将原始SVG文本节点的位置设置为多或少.

这是一个示例代码片段,说明了所有这一切.它适应您的具体示例,因此当您切换到呈现任何真实数据时,您将需要相应地修改和概括此代码段.

// Note: You will probably need to tweak these deltas
// for your labels to position nicely.
var xDelta = 35;
var yDelta = 13;
var years = ['2003','2004','2005','2006','2007','2008'];
$('text').each(function(i,el) {
  if (years.indexOf(el.textContent) != -1) {
    var g = el.parentNode;
    var x = el.getAttribute('x');
    var y = el.getAttribute('y');
    var width = el.getAttribute('width') || 50;
    var height = el.getAttribute('height') || 15;

    // A "ForeignObject" tag is how you can inject HTML into an SVG document.
    var fo = document.createElementNS("http://www.w3.org/2000/svg","foreignObject")
    fo.setAttribute('x',x - xDelta);
    fo.setAttribute('y',y - yDelta);
    fo.setAttribute('height',height);
    fo.setAttribute('width',width);
    var body = document.createElementNS("http://www.w3.org/1999/xhtml","BODY");
    var a = document.createElement("A");
    a.href = "http://yahoo.com";
    a.setAttribute("style","color:blue;");
    a.innerHTML = el.textContent;
    body.appendChild(a);
    fo.appendChild(body);

    // Remove the original SVG text and replace it with the HTML.
    g.removeChild(el);
    g.appendChild(fo);
  }
});

稍微注意一下,为方便起见,有一些jQuery可以用document.getElementsByTagName(“svg”)[0] .getElementsByTagName(“text”)替换$(‘text’).

原文地址:https://www.jb51.cc/js/152602.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐