Javascript 如何修改chartjs工具提示以便我可以在工具提示中添加自定义字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25722415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:45:38  来源:igfitidea点击:

How to modify chartjs tooltip so i can add customized strings in tooltips

javascriptchart.js

提问by Sudharshan

How do i edit chartjs tooltip to add customized strings in tooltips

我如何编辑 chartjs 工具提示以在工具提示中添加自定义字符串

enter image description here

在此处输入图片说明

For Example: I want to change the Tooltip like "January: 28 Files" or just "28 Files"

例如:我想更改工具提示,如“一月:28 个文件”或“28 个文件”

采纳答案by Sudharshan

Redefine default global tooltip template as follows:

重新定义默认的全局工具提示模板如下:

Chart.defaults.global.tooltipTemplate =
  "<%if (label){%><%=label%>: <%}%><%= value %>";

Here is another example:

这是另一个例子:

var ctx = document.getElementById("canvas").getContext("2d");

var myBarChart = new Chart(ctx).Bar(data, {
        tooltipTemplate: "<%= value %> Files"
});

回答by Benjamin Lucidarme

Validated answer doesn't work anymore. For Chart.js V2,

经过验证的答案不再有效。对于 Chart.js V2,

Chart.defaults.global.tooltipTemplate

is deprecated.

已弃用。

Instead you can use callbacks to modify the displayed tooltips. There is a sample for the usage the possible callbacks in the documentationunder Chart.defaults.global.tooltips.

相反,您可以使用回调来修改显示的工具提示。Chart.defaults.global.tooltips 下的文档中有一个使用可能的回调的示例。

In your case I would do the following:

在您的情况下,我会执行以下操作:

window.myLine = new Chart(chart, {
    type: 'bar',
    data: barChartData,
    options: {
            tooltips: {
                enabled: true,
                mode: 'single',
                callbacks: {
                    label: function(tooltipItems, data) { 
                        return tooltipItems.yLabel + ' : ' + tooltipItems.xLabel + " Files";
                    }
                }
            },
     }       
  });

Don't forget to set the HTML meta tag:

不要忘记设置 HTML 元标记:

<meta charset="UTF-8">

This answer was copy from this question.

这个答案是从这个问题复制的。

回答by John Bonfardeci

Drawing from other responses I've found that helped me, apparently the label properties can be set to functions, For example, to format currency:

从我发现对我有帮助的其他回复中提取,显然标签属性可以设置为函数,例如,格式化货币:

var overrides = {
  // show lables as currency
  scaleLabel: function(label) {
    return '$' + label.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  },

  // String - Template string for single tooltips
  tooltipTemplate: function(label) {
    return '$' + label.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  },

  // String - Template string for multiple tooltips
  multiTooltipTemplate: function(label) {
    return '$' + label.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  }
}