我有兩個 HTML 按鈕,每個按鈕都鏈接到一個特定的 JavaScript 函式。第一個按鈕觸發一個函式,代碼如下:
function add() {
var newScript = document.createElement("script");
newScript.src = "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js";
document.head.appendChild(newScript);
}
第二個按鈕觸發以下功能:
function draw() {
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
在功能編號 2 中,我使用了來自www.chartjs.org的示例。要作業,它需要頁面加載了第一個函式中參考的腳本。
單擊按鈕 1 然后單擊按鈕 2 后,我希望在我的 head 元素中看到一個腳本元素,src=https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart .js,我確實看到了,通過瀏覽器控制臺。
在我的頁面上,我希望看到(在單擊我的第二??個按鈕后)由 ChartJS 代碼生成的圖表。缺少這個元素。相反,我的控制臺中有一個錯誤,說:“圖表未在 HTMLButtonElement.draw 中定義”
Why do I have this error? Why is my chart not showing up?
Thank you for stopping by :) (y)
uj5u.com熱心網友回復:
一種hacky解決方案是將整個腳本包含在您的函式中。IE
function add() {
/*!
* Chart.js v2.9.4
* https://www.chartjs.org
* (c) 2020 Chart.js Contributors
* Released under the MIT License
*/
//The entire contents of https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js pasted here
}
uj5u.com熱心網友回復:
只需在評估您的腳本之前添加 html 腳本元素。
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<script>
function draw() {
// your draw function
}
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/348817.html
標籤:javascript html
