寻找一种在 chartjs 2.0 中的“label”元素上添加 onClick 句柄的方法,只要单击 Char.js V2.0 RadarChart 中的任何一个标签属性,使用以下方法将在 console.log 中返回“undifined”。
var data = {
// below line is the labels
labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"],
datasets: [
{
label: "My First dataset", //this only shows as legend, not label.
backgroundColor: "rgba(179,181,198,0.2)",
borderColor: "rgba(179,181,198,1)",
pointBackgroundColor: "rgba(179,181,198,1)",
pointBorderColor: "#fff",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(179,181,198,1)",
data: [65, 59, 90, 81, 56, 55, 40]
},
....
//Below is how to OnClick on chart points in chart.js V2,
//However, it didn't apply to labels, will return "undifined" .
$('#ChartV2').click(function(e) {
var activePoints = myRadarChart.getElementsAtEvent(e);
var firstPoint = activePoints[0];
console.log(firstPoint);
if (firstPoint !== undefined){
alert(firstPoint._index);
}
});
原文由 infiniteloop 发布,翻译遵循 CC BY-SA 4.0 许可协议
getElementsAtEvent
仅检查图表的 主要 元素(条形、点、扇形…)。如果您也想考虑标签,则必须重新实现标签的功能。您需要的大部分代码已在 Chart.js 库代码的不同方法中可用。只需复制粘贴/清理,如下所示。
脚本
您的点击处理程序应该是
小提琴 - http://jsfiddle.net/1Lngmtz7/