zoukankan      html  css  js  c++  java
  • 解决jquery$命名符和其它框架的冲突问题

    jquery提供了一个noConfilict的API来解决冲突。

    使用方法:

    jQuery.noConflict():运行这个函数将变量$的控制权让渡给第一个实现它的那个库。

    jQuery.noConflict(true):将$和jQuery的控制权都交还给原来的库。

     

    第一种:

       jQuery.noConflict();
       // Do something with jQuery
       jQuery("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 jQuery
       j("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 jQuery
       dom.query("div p").hide();
       // Do something with another library's $()
       $("content").style.display = 'none';
       // Do something with another version of jQuery
       jQuery("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();

  • 相关阅读:
    解决NLPIR汉语分词系统init failed问题
    牛客小白月赛3---G 旅游(树形dp)
    蓝桥杯 能量项链 (区间dp)
    OpenJ_Bailian
    LeetCode#169 Majority Element
    LeetCode#171 Excel Sheet Column Number
    LeetCode#172 Factorial Trailing Zeroes
    this指针
    auto、register、extern以及static
    const与static
  • 原文地址:https://www.cnblogs.com/ajunForNet/p/3681068.html
Copyright © 2011-2022 走看看