动态加载后不能使用jquery [英] Can't use jquery after loading it dynamically
问题描述
在我的data.js中,我正在检查a.html是否有jquery并加载它如果不。 $ j
$ b
$未定义
$ c
异常。
这是我的data.js
if(typeof jQuery =='undefined'){
var headTag = document.getElementsByTagName(head)[0];
var jqTag = document.createElement('script');
jqTag.type ='text / javascript';
jqTag.src ='http:// localhost:8001 / jquery-min.js';
headTag.appendChild(jqTag);
}
var url ='http://127.0.0.1:5000';
$ .ajax({
url:url,
success:function(data){
$(#+ containerId).html(data);
},
error:function(e){
console.log(e.message);
}
});
从开发者控制台,我可以看到jquery已加载。我可以在Resources和head标签中看到它。
解决方案 jQuery(和$因此)进行AJAX调用,因为您只是将脚本标记添加到DOM。之后它开始下载。相反,您应该绑定脚本标记的onload事件并在加载后执行操作。
示例
jqTag.onload = function(){
var url ='http://127.0.0.1:5000';
$ .ajax({
url:url,
success:function(data){
$(#+ containerId).html(data);
},
error:function(e){
console.log(e.message);
}
});
}
jqTag.src ='http:// localhost:8001 / jquery-min.js';
I'm loading data.js into my a.html page.
In my data.js, i am checking if a.html has jquery and loading it if not. Right after loading jquery i am making an ajax call but i am getting
$ is not defined
exception.
Here is my data.js
if(typeof jQuery=='undefined') {
var headTag = document.getElementsByTagName("head")[0];
var jqTag = document.createElement('script');
jqTag.type = 'text/javascript';
jqTag.src = 'http://localhost:8001/jquery-min.js';
headTag.appendChild(jqTag);
}
var url = 'http://127.0.0.1:5000';
$.ajax({
url: url,
success: function(data) {
$("#" + containerId).html(data);
},
error: function(e) {
console.log(e.message);
}
});
From developer console, i can see jquery is loaded. I can see it in both Resources and head tag.
解决方案 The jQuery (and $ thus) isn't loaded yet when you make the AJAX call since you only just added the script tag to your DOM. After that it starts the downloading. Instead you should bind the onload event of script tag and perform the actions after it has been loaded.
Example
jqTag.onload = function() {
var url = 'http://127.0.0.1:5000';
$.ajax({
url: url,
success: function(data) {
$("#" + containerId).html(data);
},
error: function(e) {
console.log(e.message);
}
});
}
jqTag.src = 'http://localhost:8001/jquery-min.js';
这篇关于动态加载后不能使用jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!