简体   繁体   English

为什么我的网站上出现参考错误和语法错误?

[英]Why am I getting a reference error and syntax error on my site?

I'm trying to set up some boilerplate code and I'm getting two errors. 我正在尝试设置一些样板代码,但出现两个错误。 The first is an unexpected token syntax error on the utils.js file and a reference error on the scripts.js file. 第一个是在一个意外标记语法错误utils.js文件和基准误差上scripts.js的文件。 Can anyone explain why these errors are returning when everything is in the right place and being referenced? 谁能解释在正确的地方并引用所有内容后为什么会返回这些错误?

HTML 的HTML

<!doctype html>
<html>
    <head>
        <link rel="stylesheet" href="styles.css">
        <script src="utils.js"></script>
        <script src="script.js"></script>
    </head>
    <body>
        <canvas id="main" width="450" height="400"></canvas>
    </body>
</html>

utils.js utils.js

var Utils = {
    utils.captureMouse = function(element){
        var mouse = {x: 0, y: 0};

        element.addEventListener("mousemove", function(event){
            var x, y;
            if(event.pageX || event.pageY){
                x = event.pageX;
                y = event.pageY;
            }
            else{
                x = event.ClientX + document.body.scrollLeft + document.documentElement.scrollLeft;
                y = event.ClientY + document.body.scrollTop + document.documentElement.scrollTop;
            }
            x -= element.offsetLeft;
            y -= element.offsetTop;
            mouse.x = x;
            mouse.y = y;
        });
        return mouse;
    }
};

script.js script.js

window.addEventListener("load", function(){
    var canvas = document.getElementById("main");
    var ctx = canvas.getContext("2d");
    mouse = Utils.captureMouse(canvas);

    canvas.addEventListener("mousedown", function(){
        console.log("X: " +mouse.x);
        console.log("Y: " +mouse.y);
    })
})

Here are the errors 这是错误

Uncaught SyntaxError: Unexpected token.             utils.js:2
Uncaught ReferenceError: utils is not defined       script.js:4
    (anonymous function) @ script.js:4

This isn't valid syntax: 这是无效的语法:

var Utils = {
  utils.captureMouse = function(){/.../}
};

On that second line, utils is not defined. 在第二行中,未定义utils And that should be setting a property, not executing an assignment operation. 那应该是设置一个属性,而不是执行赋值操作。 Perhaps you meant this?: 也许你是这个意思?:

var Utils = {
  captureMouse: function(){/.../}
};

The second error is simply a result of the first, since Utils was never effectively defined. 第二个错误只是第一个错误的结果,因为从未有效定义Utils Correcting that should correct both. 纠正该问题应同时纠正两者。

Try to attach the eventListener to document.body and not to window and/or append utils.js at the end of the body. 尝试将eventListener附加到document.body上,而不要附加到窗口和/或在主体末尾附加utils.js。 I think the problem is that the <canvas></canvas> element wasn`t created yet 我认为问题是尚未创建<canvas></canvas>元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM