Using jQuery noconflict with two versions of jQuery

后端 未结 1 1031
孤城傲影
孤城傲影 2021-01-21 11:34

The issue is that if you want to use otherLibrary on the page, $ must be otherLibrary\'s $, not jQuery\'s. Since $ is just an alias for jQuery anyway, jQuery prov

相关标签:
1条回答
  • 2021-01-21 12:34

    Quoting the example from the api, with added plugins:

    <!DOCTYPE html>
    <html>
    <head>
      <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
      <script src="jquery.superautocomplete.js"></script> <!-- this uses 1.9.1 -->
    </head>
    <body>
    
    <div id="log">
      <h3>Before $.noConflict(true)</h3>
    </div>
    <script src="http://code.jquery.com/jquery-1.3.2.js"></script>
    <script src="jquery.fancybox.js"></script> <!-- this uses 1.3.2 -->
    
    <script>
    /*
    Restore globally scoped jQuery variables to the first version loaded
    (the newer version)
    */
    jq132 = jQuery.noConflict(true);
    jq132("[rel=fancybox]").fancybox(); // using 1.3.2
    $("#autocomplete").superautocomplete(); // using 1.9.1
    </script>
    
    </body>
    </html>
    

    This is an extremely simplified version of what is going on inside jQuery when you call no conflict.

    // including first version of jQuery:
    window._foo = window.foo; // undefined
    window.foo = "1.9.1"; // 1.9.1
    
    // including second version of jQuery:
    window._foo = window.foo; // 1.9.1
    window.foo = "1.3.2"; // 1.3.2
    
    // now when you do noConflict, this happens:
    function noConflict() {
        var ret = window.foo; // 1.3.2
        window.foo = window._foo; // 1.9.1
        return ret; // 1.3.2
    }
    
    foo132 = noConflict(); // 1.3.2
    alert(foo132); //1.3.2
    alert( foo ); // 1.9.1
    
    0 讨论(0)
提交回复
热议问题