使用jQuery noconflict和两个版本的jQuery [英] Using jQuery noconflict with two versions of jQuery

查看:68
本文介绍了使用jQuery noconflict和两个版本的jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


问题是,如果你想在页面上使用otherLibrary,$必须是otherLibrary的$,而不是jQuery。因为$只是jQuery的别名,所以jQuery提供了noConflict函数,作为告诉jQuery将$的控制权返回到jQuery加载之前的任何内容的方法。

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 provides the noConflict function as a means of telling jQuery to return control of $ back to whatever had it before jQuery was loaded.

我在另一个问题上读到了这个。我正在对当前使用jQuery 1.3.2的网站进行更改,该网站无法更新,以及其他库。它目前使用noConflict,因此必须使用 jQuery 代替 $ 。我需要运行一个新版本的jQuery,以便添加到页面中。

I read this on another question. I am making a change on a site that currently uses jQuery 1.3.2, which it cannot update, and other libraries. It currently uses noConflict so that one must use jQuery in place of $. I need to run a new version of jQuery for an addition being added to the page.

如何调用第二个jQuery库并使用noConflict将新别名关联到它?所以 jQuery 适用于1.3.2,新别名适用于第二个jQuery,而$适用于其他所有内容?

How can I call this second jQuery library and use noConflict to associate a new alias to it? So that jQuery works for 1.3.2, the new alias works for the second jQuery, and $ works for everything else?

推荐答案

使用添加的插件从api引用示例:

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>

这是jQuery里面发生的简化版本你没有冲突。

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

这篇关于使用jQuery noconflict和两个版本的jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆