我正在尝试更新我的代码,以便能够在数字和百分比之间切换。
但是,我需要能够更新轴标签/tick的回调以及数据的回调。
var ctx = document.getElementById("percents").getContext('2d');
var percents_chart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ["Category 1", "Category 2", "Category 3", "Category 4"],
datasets: [{
backgroundColor: ["red", "blue", "yellow", "green"],
label: "Count",
data: percents_array
}]
},
options: {
scales: {
yAxes: [{
gridLines: {
color: "rgba(0,0,0,0)"
}
}],
xAxes: [{
ticks: {
beginAtZero: true,
callback: function (value, index, values) {
return addCommas(value) + "%";
}
}
}]
},
plugins: {
datalabels: {
display: true,
color: "#fff",
formatter: function (value, context) {
return value + '%';
}
}
},
legend: {
display: false
},
tooltips: {
mode: 'index',
intersect: false,
callbacks: {
label: function (tooltipItems, data) {
return addCommas(tooltipItems.xLabel) + "%";
}
}
},
hover: {
mode: 'nearest',
intersect: true
},
responsive: true,
title: {
fontSize: "16",
display: true,
text: 'Categories by percentage'
}
}
});
我有功能 - 更改Xaxes tick标签以添加逗号和百分比符号。 - 更改条上的数据标记以添加百分比符号。 - 更改工具提示以添加逗号和百分比符号
显然,当我切换到数字而不是百分比时,我需要逗号停留,但是要更新的百分比符号。因此,我需要在单击按钮后访问回调功能并单击一个。
。这是我当前的切换代码:(不工作(
$('.toggle-percents-numbers > button').click(function(){
$('.toggle-percents-numbers > button').removeClass('active');
$(this).addClass('active');
var type = $(this).html().toLowerCase();
percents_chart.options.title.text = "Categories by " + type;
if(type == "percentages"){
percents_chart.data.datasets[0].data = percents_array;
percents_chart.options.scales.xAxes[0].ticks.callback.label = function (tooltipItems, data) {
return addCommas(tooltipItems.xLabel) + "%";
}
} else if (type == "numbers"){
percents_chart.data.datasets[0].data = percents_array_numbers;
percents_chart.options.scales.xAxes[0].ticks.callback.label = function (tooltipItems, data) {
return addCommas(tooltipItems.xLabel);
}
}
percents_chart.update();
});
而不是修改回调,为什么不使用其中的条件,测试全局变量?
例如:
tooltips: {
mode: 'index',
intersect: false,
callbacks: {
label: function (tooltipItems, data) {
if (percent)
return addCommas(tooltipItems.xLabel) + "%";
else
return addCommas(tooltipItems.xLabel);
}
}
},
这是一个显示此方法的JSFIDDLE:https://jsfiddle.net/beaver71/nk6rz1f3/