仅当jquery已加载时才运行document.ready
我在一个全局JS文件中有这段代码仅当jquery已加载时才运行document.ready,jquery,Jquery,我在一个全局JS文件中有这段代码 $(document).ready(function() { DoStuff(); }); 不幸的是,有些页面包含此文件,但不包含jquery文件。所以我得到了错误: Message: The value of the property '$' is null or undefined, not a Function object 仅当JQuery文件已加载时,如何运行document.ready()。如何: if($){ // y
$(document).ready(function() {
DoStuff();
});
不幸的是,有些页面包含此文件,但不包含jquery文件。所以我得到了错误:
Message: The value of the property '$' is null or undefined,
not a Function object
仅当JQuery文件已加载时,如何运行document.ready()
。如何:
if($){
// your code here.
};
更新
检查
window.jQuery
而不仅仅是jQuery
。这将避免“未定义”错误。好吧,将代码封装在:
if ( $ != undefined && $ != null) {
//everything here
}
首先测试jQuery是否存在:
if(jQuery)
{
$(document).ready(function() { ... });
}
如果jQuery已加载,但仍然出现该错误,请尝试以下操作:
jQuery(function($) {
$(document).ready(function() {
DoStuff();
});
});
如果您的意思是“未加载”,则不能使用“ready()
”函数
或
是否加载?我得到
jQuery未定义
错误。我想我需要检查它是否已定义。@Tejs。当然,这里唯一的解决方案是选中if('undefined'!=typeof(jQuery)){//your code here}
。然后将所有jQuery代码封装在中,以避免被其他框架覆盖。$。这完全取决于脚本链接到生命周期的位置,与您的脚本相比。@DotnetDude,请检查我的更新(仅在FF+Firebug中测试)。@Tejs如果您愿意,请在代码中向我解释。英语不是我的母语。
jQuery(function($) {
$(document).ready(function() {
DoStuff();
});
});
if(jQuery) {
$(function() {
//...
});
}
if(typeof jQuery != 'undefined') {
$(function() {
//...
});
}