解決jquery$命名符和其它架構的衝突問題

來源:互聯網
上載者:User

jquery提供了一個noConfilict的API來解決衝突。

使用方法:

jQuery.noConflict():運行這個函數將變數$的控制權讓渡給第一個實現它的那個庫。

jQuery.noConflict(true):將$和jQuery的控制權都交還給原來的庫。

第一種:

jQuery.noConflict();// Do something with jQueryjQuery("div p").hide();// Do something with another library's $()$("content").style.display = 'none';

第二種:

jQuery.noConflict();(function($) {   $(function() {    // more code using $ as alias to jQuery  });})(jQuery);// other code using $ as an alias to the other library

第三種:

jQuery.noConflict()(function(){    // code using jQuery}); // other code using $ as an alias to the other library

第四種:

var j = jQuery.noConflict();// Do something with jQueryj("div p").hide();// Do something with another library's $()$("content").style.display = 'none';

第五種:

var dom = {};dom.query = jQuery.noConflict(true);// Do something with the new jQuerydom.query("div p").hide();// Do something with another library's $()$("content").style.display = 'none';// Do something with another version of jQueryjQuery("div > p").hide();

noConfilict的源碼:

noConflict: function( deep ) {    if ( window.$ === jQuery ) {        window.$ = _$;    }    if ( deep && window.jQuery === jQuery ) {        window.jQuery = _jQuery;    }    return jQuery;},

在jquery源碼的最開頭定義了:

(function(){   var        //     _jQuery = window.jQuery,    _$ = window.$,       // })();
為了防止$和就jQuery被覆蓋而進行儲存。

當deep為空白的時候,“_$”覆蓋“window.$”,“$”的常規功能失效,但jQuery還可以繼續使用。當有新的庫中重新定義“$”的時候,“jQuery”繼續為jQquery的常規功能,而“$”就不是jQuery中的了,它是屬於新的庫的常規功能;

當deep不為空白的時候,它將“_jQuery”覆蓋“window.jQuery”,這樣導致可能jQuery外掛程式失效;另外方法返回的jQuery,實際上沒有被覆蓋。通過它完全可以移到新的一個命名空間,如dom.query = jQuery.noConflict(true); dom.query("div p").hide();

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.