同一个站点下,兼容不同版本的JQuery Can I use multiple versions of jQuery on the same page?

Can I use multiple versions of jQuery on the same page?

回答1

Yes, it's doable due to jQuery's noconflict mode. http://blog.nemikor.com/2009/10/03/using-multiple-versions-of-jquery/

<!-- load jQuery 1.1.3 -->
<script type="text/javascript" src="http://example.com/jquery-1.1.3.js"></script>
<script type="text/javascript">
var jQuery_1_1_3 = $.noConflict(true);
</script>

<!-- load jQuery 1.3.2 -->
<script type="text/javascript" src="http://example.com/jquery-1.3.2.js"></script>
<script type="text/javascript">
var jQuery_1_3_2 = $.noConflict(true);
</script>

Then, instead of $('#selector').function();, you'd do jQuery_1_3_2('#selector').function(); or jQuery_1_1_3('#selector').function();.

 

回答2

 

After looking at this and trying it out I found it actually didn't allow more than one instance of jquery to run at a time. After searching around I found that this did just the trick and was a whole lot less code.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script>var $j = jQuery.noConflict(true);</script>
<script>
  $(document).ready(function(){
   console.log($().jquery); // This prints v1.4.2
   console.log($j().jquery); // This prints v1.9.1
  });
</script>

So then adding the "j" after the "$" was all I needed to do.

$j(function() {
  $j('.button-pro').on('click', function() {
    var el = $('#cnt' + this.id.replace('btn', ''));
    $j('#contentnew > div').not(el).animate({
      height: "toggle",
      opacity: "toggle"
    }, 100).hide();
    el.toggle();
  });
});

评论

To avoid renaming jquery variable in so many places you could just enclose your old code inside the following: (function($){ })($j) Apr 23, 2018 at 12:43
 

 

var jQuery_1_3_2 = $.noConflict(true);

The code $.noConflict(true) is used to release the global $ variable from its association with the jQuery library and restore it to its previous value. By passing true as an argument to $.noConflict(), it also releases the global jQuery variable.

The result of $.noConflict(true) is typically assigned to a new variable, in this case jQuery_1_3_2, which can then be used to reference the jQuery library without conflicting with other libraries that may also use the $ symbol.

After executing $.noConflict(true) and assigning it to jQuery_1_3_2, you would use jQuery_1_3_2 instead of $ to access the jQuery library in your code. For example:

jQuery_1_3_2(document).ready(function() {
  // Use jQuery_1_3_2 instead of $
  jQuery_1_3_2('.my-selector').addClass('active');
});

This allows you to use the specific version of jQuery referenced by jQuery_1_3_2 while preventing conflicts with other libraries that may use $.

 

posted @ 2018-07-03 11:29  ChuckLu  阅读(551)  评论(0编辑  收藏  举报