[英]How to add on click event to chart js
Hello I have a question concerning js charts.您好,我有一个关于 js 图表的问题。 I have already created one in django application and i want to generate a javascript alert by clicking a certain point in the chart.
我已经在 django 应用程序中创建了一个,我想通过单击图表中的某个点来生成一个 javascript 警报。 How can the alert get the value of the point that i choose?
警报如何获得我选择的点的值? For example with the value 92 like what is shown in the figure below:
例如,值 92 如下图所示:
This can be done with an onClick
even handler as follows:这可以使用
onClick
偶数处理程序来完成,如下所示:
onClick: (event, elements, chart) => {
if (elements[0]) {
const i = elements[0].index;
alert(chart.data.labels[i] + ': ' + chart.data.datasets[0].data[i]);
}
}
Please take a look at below runnable code and see how it works.请看下面的可运行代码,看看它是如何工作的。
new Chart('myChart', { type: 'line', data: { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [{ label: '# of Votes', data: [65, 59, 80, 81, 56, 55, 40], borderColor: '#a00' }] }, options: { onClick: (event, elements, chart) => { if (elements[0]) { const i = elements[0].index; alert(chart.data.labels[i] + ': ' + chart.data.datasets[0].data[i]); } } } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script> <canvas id="myChart" width="400" height="95"></canvas>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.