首先我們應(yīng)該知道,在jquery中,$(美元符號)就是jquery的別名,也就是說使用$和使用jquery是一樣的,在很多時候我們命名空間時,正是因為這個$而產(chǎn)生的沖突的發(fā)生。比如說:$('#xmlas')和JQuery('#xmlas') 雖然在寫法上不同,但在實際上卻是完全等同的。
要想解決這個沖突,其實最簡單的方法就是使用不同的名稱來命名,或者讓執(zhí)行代碼認為是不同的命名空間即可。
一、 jQuery庫在其他庫之前導(dǎo)入,直接使用jQuery(callback)方法如:
復(fù)制代碼 代碼如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!--先導(dǎo)入jQuery -->
<script src="../../scripts/jquery-1.3.1.js" type="text/javascript"></script>
<!--后導(dǎo)入其他庫 -->
<script src="prototype-1.6.0.3.js" type="text/javascript"></script>
</head>
<body>
<p>test---prototype</p>
<p >test---jQuery</p>
<script type="text/javascript">
jQuery(function(){ //直接使用 jQuery ,沒有必要調(diào)用"jQuery.noConflict()"函數(shù)。
jQuery("p").click(function(){
alert( jQuery(this).text() );
});
});
$("pp").style.display = 'none'; //使用prototype
</script>
</body>
</html>
二、jQuery庫在其他庫之后導(dǎo)入,使用jQuery.noConflict()方法將變量$的控制權(quán)讓渡給其他庫,有以下幾種方式:
復(fù)制代碼 代碼如下:
<script type="text/javascript">
jQuery.noConflict(); //將變量$的控制權(quán)讓渡給prototype.js
jQuery(function(){ //使用jQuery
jQuery("p").click(function(){
alert( jQuery(this).text() );
});
});
$("pp").style.display = 'none'; //使用prototype
</script>
代碼二
復(fù)制代碼 代碼如下:
<script type="text/javascript">
var $j = jQuery.noConflict(); //自定義一個比較短快捷方式
$j(function(){ //使用jQuery
$j("p").click(function(){
alert( $j(this).text() );
});
});
$("pp").style.display = 'none'; //使用prototype
</script>
代碼三
復(fù)制代碼 代碼如下:
<script type="text/javascript">
jQuery.noConflict(); //將變量$的控制權(quán)讓渡給prototype.js
jQuery(function($){ //使用jQuery
$("p").click(function(){ //繼續(xù)使用 $ 方法
alert( $(this).text() );
});
});
$("pp").style.display = 'none'; //使用prototype
</script>
復(fù)制代碼 代碼如下:
<script type="text/javascript">
jQuery.noConflict(); //將變量$的控制權(quán)讓渡給prototype.js
(function($){ //定義匿名函數(shù)并設(shè)置形參為$
$(function(){ //匿名函數(shù)內(nèi)部的$均為jQuery
$("p").click(function(){ //繼續(xù)使用 $ 方法
alert($(this).text());
});
});
})(jQuery); //執(zhí)行匿名函數(shù)且傳遞實參jQuery
$("pp").style.display = 'none'; //使用prototype
/*********************************************************************/
jQuery(document).ready(function(){ //一加載頁面的時候就將權(quán)利讓出去
jQuery.noConflict();
});
</script>
除了上面的方法之外,我們還可以采用第二種方法來解決沖突的問題,那就是最笨但最有效的解決方法:用自定義的命名空間來避免沖突。
比如說需要的項目名稱為xmlas,那么我們原來的代碼:
復(fù)制代碼 代碼如下:
$('contentArea').show()
就可以寫成以下這種形式:
復(fù)制代碼 代碼如下:
XMLAS('contentArea').show()
復(fù)制代碼 代碼如下:
jQuery(document).ready(function($) {
//你在這里可以放心的使用$了
});
當然,您也可以簡寫成下面的形式:
復(fù)制代碼 代碼如下:
jQuery(function($){
//這里為使用$的代碼
});
由此,根據(jù)第一個方法來實現(xiàn)的完整代碼如下:
復(fù)制代碼 代碼如下:
//jquery庫與其他庫沖突的完整解決辦法
<script type="text/javascript" src="photolist.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$.noConflict();
jQuery(function($) {
//使用了$的jquery代碼
});
//這里是你的其他js庫代碼
</script>
當然,你也可以對上面的完整代碼進行一步的簡化,簡化代碼如下:
復(fù)制代碼 代碼如下:
//簡化后的代碼
$.noConflict()(function(){
//這里是你的帶$的jquery代碼
});
//這里是其他庫的代碼
新聞熱點
疑難解答
圖片精選