0

假设我有一个如下页面

<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\" />");
4

1 回答 1

1

如果要动态加载该 .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
于 2013-01-04T20:21:54.587 回答