我需要在 js 文件中包含 jQuery,因为它将作为外部脚本加载。
这是我的代码:
function addjQuery() {
if (!window.jQuery) {
var jq = document.createElement("script");
jq.type = "text/javascript";
jq.src = "https://code.jquery.com/jquery-3.2.1.min.js";
document.getElementsByTagName("head")[0].appendChild(jq);
console.log("Added jQuery!");
} else {
console.log("jQuery already exists.")
}
}
addjQuery();
jQuery(function($) {
$(document).ready(function() {
});
});
但是出现错误: Uncaught ReferenceError :jQuery 未定义
即使我在 Chrome 开发工具的控制台上运行“jQuery”或“$”,它也能正常工作。
有什么问题吗?
最佳答案
jQuery()
函数在从脚本标记加载 jQuery 之前触发 - 您可以添加一个 onload
事件处理程序以在脚本下载完成时触发它:
function addjQuery() {
if (!window.jQuery) {
var jq = document.createElement("script");
jq.type = "text/javascript";
jq.src = "https://code.jquery.com/jquery-3.2.1.min.js";
document.getElementsByTagName("head")[0].appendChild(jq);
jq.onload = initjQuery;
console.log("jQuery is loaded!");
} else {
console.log("jQuery already exists.")
}
}
function initjQuery () {
jQuery(function($) {
$(document).ready(function() { });
});
}
addjQuery();
关于javascript - Uncaught ReferenceError : jQuery is not defined even working on console,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43310984/