从外部JS调用函数

编程入门 行业动态 更新时间:2024-10-09 20:28:51
本文介绍了从外部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

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调用函数

本文发布于:2023-11-26 21:33:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635273.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   JS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!