gpt4 book ai didi

javascript - Chart.js 是否可以在单击图表上的点时触发 javascript?

转载 作者:行者123 更新时间:2023-11-30 15:26:08 25 4
gpt4 key购买 nike

有谁知道在单击 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。

最佳答案

是的,你当然可以!只需使用 .getDatasetAtEvent(e).getElementsAtEvent(e)原型(prototype)方法(取决于您的需要)。以下是有关他们所做工作的更多详细信息。

Looks for the element under the event point, then returns all elements at the same data index. This is used internally for 'label' mode highlighting.

Calling getElementsAtEvent(event) on your Chart instance passing an argument of an event, or jQuery event, will return the point elements that are at that the same position of that event.

这里是一个例子,说明当有多个数据集时如何获取被点击的点。假设我的 Canvas 的 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 .

关于javascript - Chart.js 是否可以在单击图表上的点时触发 javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42939552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com