[英]Should raw javascript be in a .js file - How to include?
假设我有一个如下的页面
<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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.