我在网页上使用chartistJS绘制图表。我在chartist提供的选项中学习了"点击"功能。
请在下面找到我的代码:
public horizontalBarchartoptions = {
'onClick' : function (evt, item) {
var index = item[0]['_index']
var reportId = latestScanReportID[index];
routingFunct.navigate(["./resultPage/"+reportId]);
},
tooltips: {
callbacks: {
label: function(tooltipItem) {
return " "+ Number(tooltipItem.xLabel)+" issue(s)";
}
}
},
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Volume'
},
display: true,
labelString: 'Density',
ticks: {
mirror: true,
autoSkip: false,
padding: -30,
fontColor: '#fff'
}}],
xAxes: [{
scaleLabel: {
display: true,
labelString: '# Issues'
},
ticks: {
min: 0,
userCallback: function(label, index, labels) {
// when the floored value is the same as the value we have a whole number
if (Math.ceil(label) === label) {
return label;
}
}
},
}]
}
};
当点击一个栏时,上面的代码会重定向到该特定栏id的结果页面以下是相同的图片:在这张图片中,当点击扫描1-扫描4时,它会重定向到结果页面单击扫描5时,会引发以下异常,因为扫描5的值为0
ERROR TypeError: Cannot read property '_index' of undefined
我可以从-1开始轴标签,但这不是最好的解决方案,你能建议一种不同的方法来解决这个问题吗。
提前感谢
我建议至少在"item"没有元素时进行处理:
public horizontalBarchartoptions = {
'onClick' : function (evt, item) {
if (item != null && item != undefined) {
if (item.length > 0) {
var index = item[0]['_index']
var reportId = latestScanReportID[index];
routingFunct.navigate(["./resultPage/"+reportId]);
}
}
},
tooltips: {
callbacks: {
label: function(tooltipItem) {
return " "+ Number(tooltipItem.xLabel)+" issue(s)";
}
}
},
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Volume'
},
display: true,
labelString: 'Density',
ticks: {
mirror: true,
autoSkip: false,
padding: -30,
fontColor: '#fff'
}}],
xAxes: [{
scaleLabel: {
display: true,
labelString: '# Issues'
},
ticks: {
min: 0,
userCallback: function(label, index, labels) {
// when the floored value is the same as the value we have a whole number
if (Math.ceil(label) === label) {
return label;
}
}
},
}]
}
};
希望这能有所帮助。