因此,我正在嘗試制作一個使用 函式ChartJS獲取的變數/資料的JS 函式,它是一個 JSON 物件。我使用 try/catch 的原因是因為這里下面的兩行:
let labels = json_data.data.map(e => e.StartTime);
let data = json_data.data.map(e => e.StatusId);
如果設定了任何資料,則并不總是設定,但如果沒有,則是唯一的一組
let data = json_data.message.map(e => e.message);
除非在頁面加載時,否則沒有設定。
更改<Select>下拉串列時 JSON 物件會更改,如果其中有資料,canvas則加載該物件,但是如果用戶然后選擇沒有資料的物件,我希望嫁接為空/銷毀,但我不能這樣做,因為我'在 try catch 中,如果我也在 catch 中定義它,那么它說 ID 已經在使用中。我該怎么做才能在捕獲中“重置/銷毀”它?
function chartJSLoad(json_data) {
try {
let labels = json_data.data.map(e => e.StartTime);
let data = json_data.data.map(e => e.StatusId);
console.log(labels);
console.log(data);
var ctx = document.getElementById('canvaschartjs').getContext('2d');
var myChart = new Chart(ctx, {
data: {
datasets: [{
type: 'bar',
label: 'Bar Dataset',
data: data,
backgroundColor: 'rgba(0, 150, 90)',
borderColor: 'rgba(0, 255, 90)',
order: 2
}, {
type: 'line',
label: 'Line Dataset',
data: data,
backgroundColor: 'rgba(150, 0, 90)',
borderColor: 'rgba(255, 0, 90)',
order: 1
}],
labels: labels
},
options: {
maintainAspectRatio: false,
responsive: true,
scales: {
x: {
stacked: true,
},
y: {
stacked: true
}
}
}
});
} catch (error) {
if (typeof json_data !== 'undefined') {
myChart.destroy();
alert(json_data.message);
}
}
}
uj5u.com熱心網友回復:
您可以使用靜態方法getChart檢查具有該背景關系的圖表是否已經存在,如果存在,您將獲得可以銷毀的圖表實體:
catch (error) {
if (typeof json_data !== 'undefined') {
let chart = Chart.getChart('canvaschartjs');
if (typeof chart !== 'undefined') {
chart.destroy()
}
alert(json_data.message);
}
}
現場示例:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'orange'
}
]
},
options: {}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
let myChart = new Chart(ctx, options);
let chart = Chart.getChart('chartJSContainer');
if (typeof chart !== 'undefined') {
chart.destroy() // Does not show anything because of this line, comment it out to show again
}
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/341324.html
標籤:javascript 图表.js
上一篇:不使用等待時洗掉異步是否安全?
