注意:我知道已经有人问过类似的问题 here和 here ,但我正在寻找关于如何使这项工作或完全避免它的充分理由的更多说明。
我正在向已在使用旧版本 jQuery 库 (1.1.3.1) 的现有网站添加功能。我一直在针对最新版本的 jQuery 库 (1.4.2) 编写我添加的功能。我只使用较新版本的 jQuery 测试了该网站,但它破坏了功能,所以现在我正在考虑在同一页面上使用这两个版本。这怎么可能?
我需要在我的代码中做什么来指定我使用的是一个版本的 jQuery 而不是另一个版本?例如,我将输入 <script>
我的页面标题中有两个版本的 jQuery 标记,但是我需要做什么才能在我的调用代码中确定我调用的是库的一个版本还是另一个版本?
也许是这样的:
//Put some code here to specify a variable that will be using the newer
//version of jquery:
var $NEW = jQuery.theNewestVersion();
//Now when I use $NEW, I'll know it's the newest version and won't
//conflict with the older version.
$NEW('#personName').text('Ben');
//And when I use the original $ in code, or simply 'jquery', I'll know
//it's the older version.
$('#personName').doSomethingWithTheOlderVersion();
更新:在阅读了一些答案后,我开始怀疑尝试玩这个游戏是否是个好主意...
最佳答案
您可以使用 jQuery noConflict实现这一目标的方法。
<script type="text/javascript" src="jquery-1.1.3.js"></script>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript">
//Here, $ refers to the most recent jquery script loaded, which is version 1.4.2.
$.noConflict();
//Here, jQuery refers to 1.4.2 and $ refers to 1.1.3
//You can setup an alias like so:
var $NEW = jQuery;
//Now, you can use old jQuery with $ and new jQuery with $NEW.
</script>
关于javascript - 是否可以在同一页面上使用 2 个版本的 jQuery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2837351/