我正在尝试从外部.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
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调用函数
发布评论