开发者问题收集

类型错误:document.getElementById(…)为空

2016-06-09
1382
<html>
<head>
</head>
<body>
<h2>Example of Line Graph</h2>    
<script src="../../../Scripts/Chart.min.js"></script>
<script src="../../../Scripts/Chart.js"></script>
<script>
    var monthsData = {
        labels: ["January", "February", "March", "April", "May", "June"],
        datasets: [
        {
            fillColor: "rgba(172,194,132,0.4)",
            strokeColor: "#ACC26D",
            pointColor: "#fff",
            pointStrokeColor: "#9DB86D",
            data: [203, 156, 99, 251, 305, 247]
        }
        ]
    };
    var months = document.getElementById("chartData").getContext("2d");
    new Chart(months).Line(monthsData);
</script>
<div>
     <canvas id="chartData" width="600" height="400"></canvas>
</div>
</body>
</html>

我之前看到过关于同一问题的错误,并已更正所有错误,但我的问题尚未解决。我正在使用 chart.js 库。

3个回答

script 标记放置在包含 canvas 元素的 div 下方。

您收到错误是因为在解释和执行脚本时,画布不存在于 DOM 中。

有关脚本标记的 MDN 页面 指出:

Scripts without async or defer attributes, as well as inline scripts, are fetched and executed immediately, before the browser continues to parse the page.

话虽如此,我的答案介绍了错误的原因和简单的解决方法。查看 Satpal 的答案 ,了解更符合地道的解决方案。

Cristian Lupascu
2016-06-09

像这样更改您的代码

<html>
<head>
</head>
<body>
<h2>Example of Line Graph</h2>    
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js"></script>

<div>
     <canvas id="chartData" width="600" height="400"></canvas>
</div>
<script>
    var monthsData = {
        labels: ["January", "February", "March", "April", "May", "June"],
        datasets: [
        {
            fillColor: "rgba(172,194,132,0.4)",
            strokeColor: "#ACC26D",
            pointColor: "#fff",
            pointStrokeColor: "#9DB86D",
            data: [203, 156, 99, 251, 305, 247]
        }
        ]
    };
    var months = document.getElementById("chartData").getContext("2d");
    new Chart(months).Line(monthsData);
</script>

</body>
</html>
Vikram
2016-06-09

您遇到此问题是因为执行语句 document.getElementById("chartData") 时 DOM 尚未加载。因此无法找到元素。

您应该使用 DOMContentLoaded 事件

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

<script>
document.addEventListener("DOMContentLoaded", function(event) {
    console.log("DOM fully loaded and parsed");

    var monthsData = {
        labels: ["January", "February", "March", "April", "May", "June"],
        datasets: [
                {
                    fillColor: "rgba(172,194,132,0.4)",
                    strokeColor: "#ACC26D",
                    pointColor: "#fff",
                    pointStrokeColor: "#9DB86D",
                    data: [203, 156, 99, 251, 305, 247]
                }
            ]
    };
    var months = document.getElementById("chartData").getContext("2d");
    new Chart(months).Line(monthsData);
});
</script>
Satpal
2016-06-09