鋒利的jQuery-1--解決jquery庫和其他庫的衝突

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   ar   使用   java   strong   

在jquery中,$(貨幣符號)就是jquery的別名,也就是說使用$和使用jquery是一樣的,在很多時候我們命名空間時,正是因為這 個$而產生的衝突的發生。比如說:$(‘#xmlas‘)和JQuery(‘#xmlas‘) 雖然在寫法上不同,但在實際上卻是完全等同的。

要想解決這個衝突,其實最簡單的方法就是使用不同的名稱來命名,或者讓執行代碼認為是不同的命名空間即可。

一、jQuery庫在其他庫之後匯入,使用jQuery.noConflict()方法將變數$的控制權讓渡給其他庫,有以下幾種方式:

1.使用jQuery代替$

<script type="text/javascript">jQuery.noConflict(); //將變數$的控制權讓渡給prototype.jsjQuery(function(){ //使用jQuery  jQuery("p").click(function(){    alert( jQuery(this).text() );  });});   $("pp").style.display = ‘none‘; //使用prototype</script> 

2.定義$的別名

<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> 

3.使用jquery自動載入的方式

<script type="text/javascript">jQuery.noConflict(); //將變數$的控制權讓渡給prototype.jsjQuery(function($){ //使用jQuery  $("p").click(function(){ //繼續使用 $ 方法    alert( $(this).text() );  });});   $("pp").style.display = ‘none‘; //使用prototype</script> 或者<script type="text/javascript">jQuery.noConflict(); //將變數$的控制權讓渡給prototype.js(function($){ //定義匿名函數並設定形參為$  $(function(){ //匿名函數內部的$均為jQuery    $("p").click(function(){ //繼續使用 $ 方法      alert($(this).text());  });});})(jQuery); //執行匿名函數且傳遞實參jQuery   $("pp").style.display = ‘none‘; //使用prototype  /*********************************************************************/jQuery(document).ready(function(){ //一載入頁面的時候就將權利讓出去jQuery.noConflict();});</script> 

 

二、 jQuery庫在其他庫之前置入,直接使用jQuery(callback)方法如:

<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><!--先匯入jQuery --><script src="../../scripts/jquery-1.3.1.js" type="text/javascript"></script><!--後匯入其他庫 --><script src="prototype-1.6.0.3.js" type="text/javascript"></script></head><body><p id="pp">test---prototype <p >test---jQuery    <script type="text/javascript">jQuery(function(){ //直接使用 jQuery ,沒有必要調用"jQuery.noConflict()"函數。  jQuery("p").click(function(){    alert( jQuery(this).text() );  });});  $("pp").style.display = ‘none‘; //使用prototype</script></body></html> 

 

鋒利的jQuery-1--解決jquery庫和其他庫的衝突

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.