简体   繁体   English

无法从外部文件访问javascript函数

[英]javascript function not accessible from external file

This might be a stupid beginner's problem, but it's driving me mad. 这可能是一个愚蠢的初学者的问题,但这使我发疯。 Simplified, the code is: 简化后,代码为:

  1. I have an index.php where in an inline script (located in the head element), some JS functions are defined. 我有一个index.php,其中在嵌入式脚本(位于head元素中)中定义了一些JS函数。

     <script type="text/javascript"> $(function(){ // other code var popup = function(message,color){ $(".title").css({"color": "beige" }); $(".popup_alert").css({"background-color": color}); $( ".popup_alert" ).append(message); $(".popup_alert").removeClass("offscreen").delay(800).queue(function(){ $(this).addClass("offscreen").dequeue(); $(this).empty(); $(".title").css({"color": "#444" }); }); }; }; </script> 
  2. At the very bottom of the <body> , I'm loading an external JS file where some JQuery happens: <body>最底部,我正在加载发生一些JQuery的外部JS文件:

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

    JQuery is not the problem. jQuery不是问题。 It's loaded and the other functions inside this external file are working. 它已加载,并且此外部文件中的其他功能正在运行。

  3. Inside this linked file, I can't call the function defined in the index.php. 在此链接文件中,我无法调用index.php中定义的函数。

     popup("test",orange); 

    Will yield a console error "Uncaught ReferenceError: popup is not defined" 将产生控制台错误“未捕获的ReferenceError:未定义弹出窗口”

Is this normal? 这正常吗? I already wrapped all the stuff in ajaxToDB.js inside a $(function() { ... }); 我已经将所有内容包装在$(function(){...})内的ajaxToDB.js中; I read that this would force the page to load first, but to no avail... 我读到这将迫使页面首先加载,但无济于事...

What's the stupid detail I overlooked?! 我忽略了什么愚蠢的细节?

Thanks to @ guest271314 , I learned a lesson in JS structure: 感谢@ guest271314 ,我学习了JS结构课程:

Previously, I had wrapped the entire code within the main document's script tag inside a $(function(){}; This I thought, was "necessary" as the script tag was placed inside the head element, and the document otherwise wouldn't have been ready. 以前,我已经将整个代码包装在$(function(){};内的主文档脚本标签内$(function(){};这是“必要的”,因为脚本标签位于head元素内,否则文档不会已经准备好了。

When using another, external JS file however, this technique now prevented the external code from referring to functions declared inline, as these now "waited" for the rest of the document to be ready, including the external file (which then referred to a yet undeclared / "pending" main function). 但是,当使用另一个外部JS文件时,该技术现在可以防止外部代码引用内联声明的函数,因为这些函数现在已“等待”文档的其余部分准备就绪,包括外部文件(然后称为外部文件)。未声明/“待定”的主要功能)。

Wow. 哇。

Removing the $(function(){}; wrap and moving the script element to the bottom of the body resolved the issue. I guess that's where it should've been in the first place... level up 删除$(function(){};换行并将脚本元素移至正文底部即可解决此问题,我想这应该是应该放在第一位的地方…… 升级

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

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