我有两个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之后,我希望在我的头部元素中看到脚本元素src=https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js,我确实可以通过浏览器控制台看到它。
在我的页面上,我希望看到(在单击第二个按钮之后)由ChartJS代码生成的图形。这正是缺失的元素。相反,我的控制台中有一个错误,说:'Chart is not defined at HTMLButtonElement.draw‘
为什么我会有这个错误?为什么我的图表不显示?
感谢您的光临:) (y)
发布于 2021-11-04 22:10:56
一种hacky解决方案是在您的函数中包含整个脚本。即
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
}发布于 2021-11-04 22:25:27
只需在评估脚本之前添加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://stackoverflow.com/questions/69844866
复制相似问题