避免同其他JavaScript库的冲突
默认情况下,jQuery使用$符号作为jQuery的简写形式;若同时使用的其他JavaScript库中,使用$变量,此时就会痛jQuery发生冲突。避免冲突的方式:
将jQuery置于无冲突模式
使用另外的变量,代替$别名。
<!-- Putting jQuery into no-conflict mode. -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
var $j = jQuery.noConflict();
// $j is now an alias to the jQuery function; creating the new alias is optional.
$j(document).ready(function() {
$j( "div" ).hide();
});
// The $ variable now has the prototype meaning, which is a shortcut for
// document.getElementById(). mainDiv below is a DOM element, not a jQuery object.
window.onload = function() {
var mainDiv = $( "main" );
}
</script>
<!-- Another way to put jQuery into no-conflict mode. -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
jQuery.noConflict();
jQuery( document ).ready(function( $ ) {
// You can use the locally-scoped $ in here as an alias to jQuery.
$( "div" ).hide();
});
// The $ variable in the global scope has the prototype.js meaning.
window.onload = function(){
var mainDiv = $( "main" );
}
</script>
在其他库之前加载jQuery库
<!-- Loading jQuery before other libraries. -->
<script src="jquery.js"></script>
<script src="prototype.js"></script>
<script>
// Use full jQuery function name to reference jQuery.
jQuery( document ).ready(function() {
jQuery( "div" ).hide();
});
// Use the $ variable as defined in prototype.js
window.onload = function() {
var mainDiv = $( "main" );
};
</script>
引用jQuery函数的方式概述
创建新别名 jQuery.noConflict()方法会返回对jQuery函数的引用
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
// Give $ back to prototype.js; create new alias to jQuery.
var $jq = jQuery.noConflict();
</script>
使用立即调用函数表达式
<!-- Using the $ inside an immediately-invoked function expression. -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
jQuery.noConflict();
(function( $ ) {
// Your jQuery code here, using the $
})( jQuery );
</script>
若是用这种方式,在立即执行函数表达式中,无法使用prototype.js中的方法。
使用传递给$(document).ready()函数的参数
<script src="jquery.js"></script>
<script src="prototype.js"></script>
<script>
jQuery(document).ready(function( $ ) {
// Your jQuery code here, using $ to refer to jQuery.
});
</script>
// 简明模式
<script src="jquery.js"></script>
<script src="prototype.js"></script>
<script>
jQuery(function($){
// Your jQuery code here, using the $
});
</script>