有人知道在点击Chart.js图表上的点时是否可以触发javascript事件?
若然,怎么样?
更新:这是我当前的图表初始化脚本,基于反馈:
function RenderBasicAnalyticsChart(targetSelector, usersCreated, usersAuthenticated, contentDownloaded)
{
var ctx = $(targetSelector);
var chartObject = new Chart(ctx, {
type: 'line',
data: {
datasets: [
{
type: 'line',
label: 'Users created',
borderColor: 'rgba(0,169,224,1.0)',
pointBackgroundColor: 'rgba(0,169,224,1.0)',
backgroundColor: 'rgba(0,169,224,0.4)',
data: usersCreated
},
{
type: 'line',
label: 'Users signed in',
borderColor: 'rgba(120,170,0,1.0)',
pointBackgroundColor: 'rgba(120,170,0,1.0)',
backgroundColor: 'rgba(120,170,0,0.4)',
data: usersAuthenticated
},
{
type: 'line',
label: 'Assets downloaded',
borderColor: 'rgba(255,106,19,1.0)',
pointBackgroundColor: 'rgba(255,106,19,1.0)',
backgroundColor: 'rgba(255,106,19,0.4)',
data: contentDownloaded
}
]
},
options: {
defaultFontFamily: 'Open Sans',
responsiveAnimationDuration: 100,
scales: {
xAxes: [{
type: 'time',
time: {
displayFormats: {
quarter: 'MMM YYYY'
}
}
}]
}
}
});
$(targetSelector).click(function (e) {
var activePoints = chartObject.getElementsAtEvent(event);
if (activePoints.length > 0) {
var clickedDatasetIndex = activePoints[0]._datasetIndex;
var clickedElementIndex = activePoints[0]._index;
var value = chartObject.data.datasets[clickedDatasetIndex].data[clickedElementIndex];
console.log(clickedDatasetIndex + ' - ' + value['x']);
}
});
}
我现在遇到的问题是,无论我点击哪一行,我的 clickedDatasetIndex 总是返回0。
答案 0 :(得分:2)
是的,你确定可以!只需使用.getDatasetAtEvent(e)
或.getElementsAtEvent(e)
原型方法(根据您的需要)。这里有更详细的内容。
在事件点下查找元素,然后返回相同数据索引处的所有元素。这在内部用于“标签”模式突出显示。
在Chart实例上调用getElementsAtEvent(event),传递事件或jQuery事件的参数,将返回与该事件相同位置的点元素。
以下是有关如何获取有多个数据集时单击的点的示例。假设我的画布的id为canvas
,我的图表实例名为myLine
。
document.getElementById("canvas").onclick = function(evt){
var activePoints = myLine.getElementAtEvent(event);
// make sure click was on an actual point
if (activePoints.length > 0) {
var clickedDatasetIndex = activePoints[0]._datasetIndex;
var clickedElementindex = activePoints[0]._index;
var label = myLine.data.labels[clickedElementindex];
var value = myLine.data.datasets[clickedDatasetIndex].data[clickedElementindex];
alert("Clicked: " + label + " - " + value);
}
};
您也可以试用此codepen example。