我想为每个栏添加一个唯一的网址,然后点击其中一个栏打开该网址。但在我的情况下,我有两个数据集。我正在使用onClick事件返回两个数据集的活动记录。
我正在使用以下代码..它将返回两个数据集对象...它应该只返回一个数据集。
<script>
var barChartData = {
labels: ["Jan","Feb","March"],
datasets: [{
label : "Quoted",
backgroundColor : "#FF7228",
data : [50,20,70],
},
{
label : "Accepted",
backgroundColor : "#FFCC8C",
data : [30,10,20],
},
]
};
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
events:['click'],
onClick:function(c,i){
console.log(this.active);
}
},
responsive: true,
legend: {
position: 'top',
},
}
});
};
</script>
答案 0 :(得分:2)
您可以使用getElementAtEvent()
方法仅返回一个数据集。然后,您可以应用更多逻辑来检测单击的栏。
<强>ᴅᴇᴍᴏ强>
var barChartData = {
labels: ["Jan", "Feb", "March"],
datasets: [{
label: "Quoted",
backgroundColor: "#FF7228",
data: [50, 20, 70],
}, {
label: "Accepted",
backgroundColor: "#FFCC8C",
data: [30, 10, 20],
}]
};
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
onClick: function(e) {
var bar = this.getElementAtEvent(e)[0];
var index = bar._index;
var datasetIndex = bar._datasetIndex;
// check which bar is clicked
if (index == 0 && datasetIndex == 0) alert('First BAR Clicked!');
else if (index == 0 && datasetIndex == 1) alert('Second BAR Clicked!');
else if (index == 1 && datasetIndex == 0) alert('Third BAR Clicked!');
else if (index == 1 && datasetIndex == 1) alert('Fourth BAR Clicked!');
else if (index == 2 && datasetIndex == 0) alert('Fifth BAR Clicked!');
else if (index == 2 && datasetIndex == 1) alert('Sixth BAR Clicked!');
}
},
responsive: true,
legend: {
position: 'top',
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>
答案 1 :(得分:0)
如果您想了解基础数据,请在Grunt的答案上进一步构建,因此请考虑仅使用onclick代码:
var barChartData = {
labels: ["Jan", "Feb", "March"],
datasets: [{
label: "Quoted",
backgroundColor: "#FF7228",
data: [50, 20, 70],
}, {
label: "Accepted",
backgroundColor: "#FFCC8C",
data: [30, 10, 20],
}]
};
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
onClick: function(e) {
var bar = this.getElementAtEvent(e)[0];
if (bar != undefined) {
var index = bar._index;
var datasetIndex = bar._datasetIndex;
alert(barChartData.datasets[datasetIndex].data[index].x +
', ' + barChartData.datasets[datasetIndex].data[index].y);
}
}
},
responsive: true,
legend: {
position: 'top',
},
});