Answers:
if (typeof jQuery != 'undefined') {
// jQuery is loaded => print the version
alert(jQuery.fn.jquery);
}
jQuery.fn.jquery
和jQuery().jquery
(简写:)$.fn.jquery
$().jquery
。如果您想更深入地了解,我用指向jquery源代码的链接详细介绍了它。
if (window.jQuery) { // jQuery is loaded => print the version alert(jQuery.fn.jquery); }
!==
您可以只检查jQuery
对象是否存在:
if( typeof jQuery !== 'undefined' ) ... // jQuery loaded
jQuery().jquery
有版本号。
至于前缀,jQuery
应该始终有效。如果要使用$
,可以将代码包装到一个函数中,并将jQuery
其作为参数传递给它:
(function( $ ) {
$( '.class' ).doSomething(); // works always
})( jQuery )
if( jQuery )
如果将抛出一个异常jQuery
是未知的,它不会工作。
try {...}catch(e){...}
?
jQuery().jquery
。它创建了一个jQuery对象。(从另一个答案抄评论)
$.fn.jquery
// If there is concern that there may be multiple implementations of `$` then:
jQuery.fn.jquery
如果您获取版本号(通常是字符串),则jQuery将被加载,这就是您正在使用的版本。如果未加载,则应该返回
undefined
,甚至可能出错。
很老的问题,我已经看到一些人在评论中提到了我的答案。但是,我发现,有时由于注释而留下的出色答案可能会被忽略;尤其是当答案中有很多评论时,您可能会发现自己在寻找他们的宝石时,正在钻研它们。希望这可以帮助某人!
…只是因为到目前为止尚未提到此方法-打开控制台并键入:
$ === jQuery
由于上述@Juhana $().jquery
将返回版本号。
($ === jQuery)?$().jquery:'no jquery';
我发现这是检查jQuery是否已加载的最短和最简单的方法:
if (window.jQuery) {
// jQuery is available.
// Print the jQuery version, e.g. "1.0.0":
console.log(window.jQuery.fn.jquery);
}
http://html5boilerplate.com等使用此方法。
我的偏好是:
console.debug("jQuery "+ (jQuery ? $().jquery : "NOT") +" loaded")
结果:
jQuery 1.8.0已加载
您实际上应该将其包装在IE的try / catch块中:
// Ensure jquery is loaded -- syntaxed for IE compatibility
try
{
var jqueryIsLoaded=jQuery;
jQueryIsLoaded=true;
}
catch(err)
{
var jQueryIsLoaded=false;
}
if(jQueryIsLoaded)
{
$(function(){
/** site level jquery code here **/
});
}
else
{
// Jquery not loaded
}
typeof jQuery != 'undefined'
?是对每个IE还是对较旧的IE都是如此?
转到开发者的工具>控制台,并编写以下命令之一
jQuery.fn.jquery
console.log(jQuery().jquery);
按照Template Monster Blog的输入,下面的这些脚本将为您提供您现在正在遍历的站点中的jquery版本。
1. console.log(jQuery.fn.jquery);
2. console.log(jQuery().jquery);