jQuery.noConflict( )

Posted rosendolu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jQuery.noConflict( )相关的知识,希望对你有一定的参考价值。

jQuery.noConflict( )

Query.noConflict( [removeAll ] )

removeAll

Type: Boolean (default:false)

A Boolean indicating whether to remove all jQuery variables from the
global scope (including jQuery itself).

$.noConflict( )

  1. $.noConflict( ) default:false

Return control of $ back to the front library

<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script> 
$.noConflict();
// Code that uses other library's $ can follow here.
</script>

Pass $ to the ready() callback function,within you can use $

<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
$.noConflict();
jQuery( document ).ready(function( $ ) {
  // Code that uses jQuery's $ can follow here.
});
// Code that uses other library's $ can follow here.
</script>
jQuery.noConflict();
(function( $ ) {
  $(function() {
    // More code using $ as alias to jQuery
  });
})(jQuery);
 
// Other code using $ as an alias to the other library

Create a different alias instead of jQuery to use in the rest of the script.

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

Completely move jQuery to a new namespace in another object.

var dom = {};
dom.query = jQuery.noConflict( true );
  1. $.noConflict( true )

Return the globally scoped jQuery $ variables to the front version.

<script src="jQuery1.1.js"></script>
<script src="jquery3.0.js"></script>
<script>
$.noConflict(true);
// Code that uses another version`s "jQuery" "$" can follow here.
</script>

Example

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
 
<div id="log">
  <h3>Before $.noConflict(true)</h3>
</div>
<script src="https://code.jquery.com/jquery-1.6.2.js"></script>
 
<script>
var $log = $( "#log" );
 
$log.append( "2nd loaded jQuery version ($): " + $.fn.jquery + "<br>" );
 
// Restore globally scoped jQuery variables to the first version loaded
// (the newer version)
 
jq162 = jQuery.noConflict( true );
 
$log.append( "<h3>After $.noConflict(true)</h3>" );
$log.append( "1st loaded jQuery version ($): " + $.fn.jquery + "<br>" );
$log.append( "2nd loaded jQuery version (jq162): " + jq162.fn.jquery + "<br>" );
</script>
 

Outcome

Before $.noConflict(true)
2nd loaded jQuery version ($): 1.6.2
After $.noConflict(true)
1st loaded jQuery version ($): 1.10.2
2nd loaded jQuery version (jq162): 1.6.2

References
http://api.jquery.com/jQuery.noConflict/

SourceCode
jQuery.noConflict()

以上是关于jQuery.noConflict( )的主要内容,如果未能解决你的问题,请参考以下文章

Mailchimp 的 $mcj = jQuery.noConflict(true) 导致冲突

jquery.noConflict源码分析

window.onload多个共存 - 借鉴jQuery.noConflict的思路

jquery noConflict()

jQuery.noConflict( )

jquery noConflict()方法