Chart.js第2686行错误

Chart.js line 2686 Error

本文关键字:错误 2686行 js Chart      更新时间:2023-09-26

我想要我的sinatra应用程序中的lineChart of Chart.js。但firefox控制台显示

`TypeError:this.scale is undefined(Chart.js:2686)`

并且,lineChart不显示。我写了以下代码。

@你好.erb

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
        <script src="Chartjs/Chart.js" type="text/javascript"></script>
        <script src="script.js" type="text/javascript"></script>
    </head>
    <body>
        <canvas id="line" height="450" width="600"></canvas>
    </body>
</html>

@script.js

$(function(){
    var lineChartData = {
    labels : ["hoge","fuga"],
    datasets : [
    {
        fillColor : "rgba(220,220,220,0.5)",
        strokeColor : "rgba(220,220,220,1)",
        pointColor : "rgba(220,220,220,1)",
        pointStrokeColor : "#fff",
        data : [60,70]
    } ]
}
var myLine = new Chart(document.getElementById("line").getContext("2d")).Line(lineChartData);
});

当我用NOT sinatra(erb)编写这段代码时,它工作正常。我应该修改什么?

检查浏览器的开发工具(通常按F12),并在"网络"选项卡中查看文件是否正确加载-按F5重新加载页面。可能是您的脚本文件没有加载,在这种情况下,请在前面加一个斜杠(<script src='/script.js' ...>)。javascript文件是否位于您的public目录中?

您的问题看起来像是一个时间问题。由于您的画布元素在脚本运行时不存在。

使用Jquery,您可以将图表语句封装在文档中。准备

$( document ).ready(function() {
     var myLine = new Chart(document.getElementById("line").getContext("2d")).Line(lineChartData);
}

对于非Jquery解决方案,我推荐https://stackoverflow.com/a/9899701/1279355