简体   繁体   English

从外部 js 文件运行 function 的问题

[英]Issue running function from external js file

I am trying to do something which I feel should be elementary and basic but it is not working.我正在尝试做一些我认为应该是基本和基本的事情,但它不起作用。 I have looked at many related Stackoverflow QAs but none covers this exact issue.我查看了许多相关的 Stackoverflow QA,但没有一个涵盖这个确切的问题。

I want to run a function from an external js file called main.js.我想从名为 main.js 的外部 js 文件运行 function。 The file is loaded at the bottom of the body section of an html page in the usual way.该文件以通常的方式加载到 html 页面的正文部分的底部。 All contents of the file is within the standard jQuery wrappers.该文件的所有内容都在标准 jQuery 包装器中。 I know it is loading properly because I can see it in Developer Tools and various animations coded in it are running correctly.我知道它正在正确加载,因为我可以在开发人员工具中看到它,并且其中编码的各种动画运行正常。 I have jQuery 3.3.1 loaded in the head section of the page and again it must be loading properly because the animations are working.我在页面的头部加载了 jQuery 3.3.1 并且它必须再次正确加载,因为动画正在运行。

As a test I have the following function in main.js:作为测试,我在 main.js 中有以下 function:

function alerttest() {
  alert('Function test works');
}

Then in the main body of the html page I call the function as follows:然后在html的主体页面我调用function如下:

<script>
  alerttest();
</script>

So when I refresh the page I should get an alert but this does not happen.因此,当我刷新页面时,我应该会收到警报,但这不会发生。 I get an error in the console: Uncaught ReferenceError: alerttest is not defined .我在控制台中收到错误: Uncaught ReferenceError: alerttest is not defined This would happen if I loaded scripts in the wrong location so I also tried this to call the function so the DOM would be loaded first:如果我在错误的位置加载脚本会发生这种情况,所以我也尝试调用 function 以便首先加载 DOM:

<script>
$(function() {
  alerttest();
});
</script>

but I get the same Reference error.但我得到相同的参考错误。 Can anyone suggest what is going on?谁能建议发生了什么?

Environment: Windows 10, VSCode, Codeigniter 3, jQuery 3.3.1, WAMP with PHP 7.4.7环境:Windows 10,VSCode,Codeigniter 3,jQuery 3.3.1,WAMP 与 Z2FEC392304A7FCB72C32FEC392304A77923AC。

I believe I have solved the problem and, as I suspected, it was about the location of scripts.我相信我已经解决了这个问题,并且正如我所怀疑的那样,它与脚本的位置有关。 I have always been advised to include scripts at the bottom of the page just above the closing body tag but this didn't work in this instance.我一直被建议在页面底部的结束正文标记上方包含脚本,但这在这种情况下不起作用。 I have now located my main.js in the head section along with the jQuery CDN and everything works just fine.我现在已将 main.js 与 jQuery CDN 一起放在 head 部分,一切正常。

Many thanks for responding.非常感谢您的回复。

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

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