原始javascript应该在.js文件中吗-如何包含

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

本文关键字:何包含 文件 js javascript 原始      更新时间:2023-09-26

假设我有一个像下面这样的页面

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

和我的file.js文件只是包含没有包装的原始jQuery事件。具体如下:

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

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

这根本不起作用。当我将file.js的内容直接包含到HTML中时,它可以正常工作,但是JS似乎没有被正确包含。我试过把"alert(3);"放在file.js的顶部,但它没有触发。我尝试了以下操作:

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

如果你想动态加载。js文件,修改代码如下:

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

查看控制台

中是否出现错误

它可能是,你是,例如,使用mod_rewrite和jQuery试图加载脚本相对于"文件夹"你的子页面是在。例如:您是@ http://www.example.com/link-to-subpage/。在这种情况下,jQuery将尝试加载http://www.example.com/link-to-subpage/js/file.js,而它驻留在@ http://www.example.com/js/file.js。在这种情况下,使用绝对路径。所以,不是:

js/file.js

写:

/js/file.js