Chart.js自定义tooltipTemplate索引

时间:2015-08-31 13:58:45

标签: javascript chart.js

我用Chart.js制作了这张图表。

var data = {
  labels: ["", "", "", "2015-08-28", "2015-08-29", "2015-08-30", "2015-08-31", ],
  websites: ["", "", "", "gamesoutletCrawler", "gamesoutletCrawler", "G2PLAY", "instantgaming", ],
  datasets: [{
    label: "Best price last 7 days",
    fillColor: "rgba(220,220,220,0.2)",
    strokeColor: "rgba(220,220,220,1)",
    pointColor: "rgba(220,220,220,1)",
    pointStrokeColor: "#fff",
    pointHighlightFill: "#fff",
    pointHighlightStroke: "rgba(220,220,220,1)",
    data: [0, 0, 0, 34.5, 36.8, 37.3, 37.99, ]
  }]
};

window.onload = function() {
  var ctx = document.getElementById("chartkeys").getContext("2d");
  window.myLine = new Chart(ctx).Line(data, {
    responsive: true,
    tooltipTemplate: "<%= data.websites[idx] %>",
    scaleLabel: "<%= Number(value).toFixed(2).replace('.', ',') + ' €'%>"
  });
}

在我的工具提示模板上,我想使用data.websites中的值,但我不知道如何传入我的tooltip数组的索引。这不起作用:

<%= data.websites[idx] %>

idx错了,它不是系统使用的索引。当你将鼠标悬停在图表上时,知道我在这里要写什么来显示索引工具提示吗?

如果我写<%= data.websites %>,它会向我展示阵列中的所有网站,而不是那个悬停的网站。

1 个答案:

答案 0 :(得分:3)

您可以使用函数而不是模板字符串

...
tooltipTemplate: function (d) {
    return data.websites[data.labels.indexOf(d.label)]
},
...

请注意,这需要标签是唯一的,或者如果有重复的标签,那么哪个标签处于活动状态并不重要(例如,在您的数据中,前3个标签是相同的,但不会导致任何问题,因为websites数组中的前3个条目也是相同的。如果它们不同,这个方法将不起作用)