当点击特定数据集的堆栈时,我正在尝试获取堆积条形图中与数据集关联的标签的名称。
这是我的代码:
var dataPack1 = [100, 200, 300, 400, 500];
var dataPack2 = [150, 450, 350, 250, 150];
var dates = ["May 1", "May 2", "May 3", "May 4", "May 5"];
var bar_chart = new Chart(bar_ctx, {
type: 'bar',
data: {
labels: dates,
datasets: [
{
label: 'Bowser',
data: dataPack1,
backgroundColor: "grey"
},
{
label: 'Mario',
data: dataPack2,
backgroundColor: "maroon"
},
]
},
options: {
scales: {
xAxes: [{
stacked: true,
gridLines: { display: false },
}],
yAxes: [{
stacked: true
}],
}, // scales
onClick: function(evt, element) {
//var val = element.something such that val is assigned 'Bowser'
}
} // options
}
);
现在,当我点击说,500,我想要一个变量,val来指定'Bowser'。那可能吗?
Here是jsfiddle。
答案 0 :(得分:0)
你可以使用原型方法.getElementAtEvent(e)
来点击元素
onClick: function(evt, element) {
var activePoints = bar_chart.getElementAtEvent(evt);
console.log(activePoints[0]._model.datasetLabel);
}
或者您可以将其作为事件处理程序附加到图表元素
bar_ctx.onclick = function(evt) {
var activePoints = bar_chart.getElementAtEvent(evt);
console.log(activePoints[0]._model.datasetLabel);
};