从外部JS调用函数 [英] Calling function from external JS

查看:350
本文介绍了从外部JS调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to call a function from an external .js file but the console is returning errors and the function is not being called. How do I correct my code and be able to call the function properly.

这是主要的.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



EDIT

I am getting 2 errors in the console:

Error 1

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



错误2
< br>


Error 2

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


推荐答案

更改此信息:

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

到此:

window.onload = xyz.makeShape.Circle;

window.onload 需要设置为一个函数引用,而不是调用函数的结果。

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

你也不能从这两行做在加载DOM之前< head> 部分:

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');

您需要在加载DOM后执行这些操作。这样做有多种可能的策略。您已经拥有的最简单的方法是在onload处理程序中执行它们,因为您知道DOM已经加载到那里。您还可以将加载外部.js文件的脚本标记移动到< body> 部分的末尾,并且DOM已经准备就绪,然后该js文件运行。

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.

这篇关于从外部JS调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆