简体   繁体   English

原始javascript是否应位于.js文件中-如何包含?

[英]Should raw javascript be in a .js file - How to include?

Suppose I have a page such as the following 假设我有一个如下的页面

<html><head></head><body><!--STUFF-->
   <script>
       if(SomeBooleanVariable) {
           $.getScript('js/file.js');
       }
    </script>
 </body></html>

and my file.js file simply contains raw jQuery events with no wrapping. 而我的file.js文件仅包含原始jQuery事件,没有任何包装。 It is exactly as follows: 内容如下:

 $(document).on("eventHere", "classHere", function(e) {
   //Stuff
 });


 $(document).on("eventHere", "classHere", function(e) {
   //Stuff
 });

This is simply not working. 这根本行不通。 When I include the contents of file.js directly into the HTML it works fine however the JS does not seem to be included properly. 当我将file.js的内容直接包含到HTML中时,它可以正常工作,但是JS似乎未正确包含。 I have tried putting "alert(3);" 我试过把“ alert(3);” at the top of file.js but it does not fire. 在file.js的顶部,但不会触发。 I have tried the following: 我尝试了以下方法:

 $("head").append("<script src=\"js/file.js\" />");
 $(document).append("<script src=\"js/file.js\" />");
 -and-
 document.write("<script src=\"js/file.js\" />");

If you want to load that .js file dynamically, change your code to this: 如果要动态加载该.js文件,请将代码更改为此:

if(SomeBooleanVariable) {
    $.getScript("ajax/test.js")
    .done(function(script, textStatus) {
        console.log(textStatus);
    })
    .fail(function(jqxhr, settings, exception) {
        console.log("Triggered ajaxError handler.");
    });  

And see if you get any error in console 看看您是否在控制台中遇到任何错误

It may be, that you are, for example, using mod_rewrite and jQuery tries to load script relative to the "folder" your subpage is in. Example: you are @ http://www.example.com/link-to-subpage/ . 例如,您可能正在使用mod_rewrite,而jQuery尝试加载相对于您子页面所在的“文件夹”的脚本。示例:您位于@ http://www.example.com/link-to-subpage / In this case, jQuery will try to load http://www.example.com/link-to-subpage/js/file.js , while it resides @ http://www.example.com/js/file.js . 在这种情况下,jQuery将尝试加载http://www.example.com/link-to-subpage/js/file.js ,而它驻留@ http://www.example.com/js/file.js In this case, use an absolute path. 在这种情况下,请使用绝对路径。 So, instead of: 因此,代替:

js/file.js

write: 写:

/js/file.js

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

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