问题是,如果你想在页面上使用otherLibrary,$必须是otherLibrary的$,而不是jQuery。因为$只是jQuery的别名,所以jQuery提供了noConflict函数,作为告诉jQuery将$的控制权返回给jQuery加载之前的任何内容的方法。
我在另一个问题上读到了这个。我正在对当前使用jQuery 1.3.2的网站进行更改,该网站无法更新,以及其他库。它目前使用noConflict,因此必须使用jQuery
代替$
。我需要运行一个新版本的jQuery,以便添加到页面中。
如何调用第二个jQuery库并使用noConflict将新别名与其关联?因此jQuery
适用于1.3.2,新别名适用于第二个jQuery,而$适用于其他所有内容?
答案 0 :(得分:3)
使用添加的插件从api引用示例:
<!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内容。
// 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