jQuery.noConflict
会重置$
变量,使其不再是jQuery
的别名。除了只调用一次之外,你真正需要做的事情并不多。但是,如果你愿意,你可以使用返回值创建自己的别名:
var jq = jQuery.noConflict();
通常情况下,您需要在引入jQuery和任何插件之后立即执行此操作:
<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript" src="/path/to/jquery-plugin.js"></script>
<script type="text/javascript">
jQuery.noConflict();
// Code that uses other library's $ can follow here.
</script>
<script type="text/javascript" src="/path/to/prototype.js"></script>
你还可以更进一步,使用 noConflict(true)
释放掉 jQuery
。不过,如果你选择这种方式,你肯定需要一个别名,因为既不 $
也不 jQuery
可能是你想要的:
var jq = jQuery.noConflict(true);
我认为这个最后的选项主要用于混合jQuery的不同版本,特别是在更新jQuery本身时希望更新过时插件的情况下。
<script type="text/javascript" src="jquery-1.4.4.js"></script>
<script type="text/javascript" src="jquery-older-plugin.js"></script>
<script type="text/javascript">
var jq144 = jQuery.noConflict(true);
</script>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
<script type="text/javascript" src="jquery-newer-plugin.js"></script>