图表JS:在工具提示模板中使用函数

Chart JS: Use function in tooltip template

本文关键字:函数 JS 工具提示 图表      更新时间:2023-09-26

我有一系列表示货币的数据,我需要工具提示来显示数据系列并格式化数据。我有一个工作函数,将"123456.78"转换为"123,456.78",但我不能在工具提示中应用它。我的代码如下:

function formatMoney(n, c, d, t){
  var c = isNaN(c = Math.abs(c)) ? 2 : c,
      d = d == undefined ? "." : d,
      t = t == undefined ? "," : t,
      s = n < 0 ? "-" : "",
      i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
      j = (j = i.length) > 3 ? j % 3 : 0;
     return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/('d{3})(?='d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
   };
  var lineChartData = {
        labels : ['January', 'Ferbruary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    datasets : [
      {
        label: "Value",
        fillColor : "rgba(32,78,158,0.2)",
        strokeColor : "rgba(32,78,158,1)",
        pointColor : "rgba(32,78,158,1)",
        pointStrokeColor : "#fff",
        pointHighlightFill : "#fff",
        pointHighlightStroke : "rgba(32,78,158,1)",
        data : ['20000','22000','35000','17000','18000','47500','20000','22000','35000','17000','18000','47500']
      },{
        label: "Budget",
        fillColor: "rgba(47,116,234,0.3)",
        strokeColor: "rgba(47,116,234,1)",
        pointColor: "rgba(47,116,234,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(47,116,234,1)",
        data : ['10000','20000','30000','7000','17000','40500','19000','20000','33000','12000','17500','40500']
    },
    ]
  }
  var ctx = document.getElementById("money-graph").getContext("2d");
  window.myLine = new Chart(ctx).Line(lineChartData, {
    responsive: true,
    maintainAspectRatio: true,
    multiTooltipTemplate: "<%= datasetLabel %> £<%= formatMoney(value,2) %>"
  });

我在控制台得到的错误是ReferenceError: Can't find variable: formatMoney

我还尝试将函数定义为var formatMoney = function(n, c, d, t)

我正在做这个答案,以便将来更容易找到参考。问题是模板引擎不能处理函数,或者类似的问题。但是使用另一种模板方式似乎可以工作:

multiTooltipTemplate: function(chartData){
  return chartData.label+" : " + formatMoney(chartData.value, 2);
}