在同一个HTML页面中有两个不同版本的JQuery

use*_*436 6 html javascript jquery

我有一个HTML文档,我在thickbox的标题中引用了jQuery版本1.2.2,后来我在</body>标记之前引用了jQuery 1.7.1 ,用于图片幻灯片放映.

问题是,除非删除jQuery 1.7.1的引用然后停止幻灯片工作,否则thickbox将无法工作.

我已经google了解了解$冲突,但没有一个建议的解决方案有效.

我见过并尝试过的最常见的是: var $j = jQuery.noConflict();

我该如何解决这个问题?

T.J*_*der 2

如果插件表现良好,那么这应该可以工作:

<script src="jquery-1.2.2.js"></script>
<script src="thickbox.js"></script>
<script src="jquery-1.7.1.js"></script>
<script src="slideshow.js"></script>
Run Code Online (Sandbox Code Playgroud)

(显然这些脚本名称是编造的。)这是一个示例源代码)(我使用了 jQuery 1.4.2 和 jQuery 1.7.1,因为 Google 不托管 1.2.2)。

上面的代码适用于行为良好的插件,因为行为良好的插件根本不依赖全局变量$,而是使用jQuery全局变量加载时的值,并在闭包,然后在整个插件代码中使用该本地引用,如下所示:

// Example plug-in setup
(function($) {
    // ...Plug-in code using `$` here -- note it's a *local* `$`,
    // not the global `$`, and not the global `jQuery`...
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

或者

(function() {
    var $ = jQuery;

    // ...Plug-in code using `$` here -- note it's a *local* `$`,
    // not the global `$`, and not the global `jQuery`...
})();
Run Code Online (Sandbox Code Playgroud)

这两个都在加载插件时获取全局jQuery值,然后在整个过程中使用它们的本地别名。

如果插件想要等待ready事件,也可以这样做:

jQuery(function($) {
    // ...Plug-in code using `$` here -- note it's a *local* `$`,
    // not the global `$`, and not the global `jQuery`...
});
Run Code Online (Sandbox Code Playgroud)

...它使用传递到就绪处理程序中的 jQuery 函数。

按照上面列出的脚本加载顺序,这三个中的任何一个都可以正常工作(厚盒看到 jQuery 1.2.2,幻灯片看到 jQuery 1.7.1)。

但我开场白中的“如果”是一个很大的“如果”。很多插件并不是以这种方式编写的。


尽管如此,我还是会放弃任何需要jQuery 1.2.2 才能工作的插件,并尽可能(而且几乎总是可能)避免加载任何库的两个不同版本,包括 jQuery。同一页。