1

我正在尝试从外部 .js 文件调用函数,但控制台返回错误并且未调用该函数。如何更正我的代码并能够正确调用该函数。

这是主要的 .html 文件:

<html>
<head>
    <script type="text/javascript" src="xp.js">
    </script>
    <script type="text/javascript">
        window.onload = xyz.makeShape.Circle();
    </script>
</head>
<body>
    <canvas id="xyz" width="600" height="600"></canvas>
</body>
</html>

这是 .js 文件:

var xyz = xyz || {};
var canvas = document.getElementById('xyz');
var context = canvas.getContext('2d');
xyz.makeShape = {
    Circle : function() {
        console.log('working');
    }
}



编辑

我在控制台中收到 2 个错误:

错误 1

TypeError: canvas is null
window.onload = xyz.makeShape.Circle;


错误 2

TypeError: xyz.makeShape is undefined
window.onload = xyz.makeShape.Circle;
4

3 回答 3

5

Change this:

window.onload = xyz.makeShape.Circle();

to this:

window.onload = xyz.makeShape.Circle;

window.onload needs to be set to a function reference, not to the results of calling a function.


You also can't do these two lines from the <head> section before the DOM is loaded:

var canvas = document.getElementById('xyz');
var context = canvas.getContext('2d');

You need to execute those after the DOM has been loaded. There are multiple possible strategies for doing that. The easiest for what you already have would be to execute them in your onload handler since you know the DOM is already loaded there. You could also move the script tag that loads your external .js file to the end of the <body> section and the DOM will already be ready then when that js file runs.

于 2013-03-30T18:33:52.200 回答
0

您只需要js使用标签包含文件<script>- 在页眉或页脚中。

<script type="text/javascript" src="js/yourjsfile.js"></script>

现在您可以从该脚本调用函数,就好像它们在当前文件中一样

编辑

如果您确定该文件已被包含(首先确保您的路径正确),那么您需要检查您的控制台是否存在可能由包含文件引起的错误。您提供的代码看起来正确。

于 2013-03-30T18:29:14.250 回答
0

External js:

var xyz = xyz || {};
xyz.makeShape = {
    Circle: function () {
        console.log('working');
    }
}

Internal js:

window.onload = function () {
    var canvas = document.getElementById('xyz');
    var context = canvas.getContext('2d');
    xyz.makeShape.Circle();

}

Tested and works

于 2013-03-30T18:56:30.383 回答