使用不同的Jquery版本没有冲突

时间:2012-04-02 12:54:38

标签: javascript jquery jquery-plugins

所以,让我们从情况开始。我有一个网站使用Jquery 1.4.2作为Jquery的主要版本。 但是用户可以使用使用其他版本(1.2.1,1.5.1等)的自定义模板。因此在某些情况下会带来冲突 例如,这里

//included in my main view
<script type="text/javascript" src="jquery-1.4.2.min.js" ></script>
<script type="text/javascript">
        $(function () {
              alert($().jquery);
          });
</script>

//included in custom template
<script type='text/javascript' src='jquery-1.5.1.min.js'></script>
<script type="text/javascript">
        $(function () {
          alert($().jquery);
        });
</script>

因此他们都警告 1.5.1 (因为在文档准备好时初始化)。所以我想防止这种情况发生。

现在我只能得到一个解决方案 - 使用noConflict(true)并将所有$Jquery符号更改为所有插件中的新符号在我的网站。
是否有更优雅的解决方案,或者我真的需要重命名我网站中使用的所有插件?

P.S。另一种方式可能是使用向后兼容性插件,但在这种情况下,我需要包含大量插件,以使其与所有版本兼容。

1 个答案:

答案 0 :(得分:5)

查看jQuery.noConflict()

**//included in my main view**
<script type="text/javascript" src="jquery-1.4.2.min.js" ></script>
<script type="text/javascript">
        $(function () {
              alert($().jquery);
          });
</script>

**//included in custom template**
<script type='text/javascript' src='jquery-1.5.1.min.js'></script>
<script type="text/javascript">
        $151 = jQuery.noConflict();
        $151(function ($) { // In this scope $ === $151, or jQuery 1.5.1
          alert($().jquery);
          // $ !== jQuery.
          // $().jquery = 1.5.1
          // jQuery().jquery = 1.4.2
        });
        // outside the scope
        // $ === jQuery
        // $().jquery returns 1.4.2
</script>

如何使用jQuery.noConflict();

$.noConflict()返回jQuery的副本,你可以像这样捕获变量:

var j = $.noConflict()

HTML:

<script type="text/javascript" src="jquery-1.4.2.min.js" ></script>
<script type='text/javascript' src='jquery-1.5.1.min.js'></script>

JavaScript的:

// jQuery === $
//$().jquery === 1.5.1

jQ151 = $.noConflict();

// jQ151 !== $
// jQ151().jquery === 1.5.1
// $().jquery === 1.4.2

jQuery.ready(function() {..或简称jQuery(function() {..中,第一个参数是jQuery的本地副本:

<script type="text/javascript" src="jquery-1.4.2.min.js" ></script>
<script type="text/javascript">
    jQuery(function($) {
        // in this scope $ refers to jQuery version 1.4.2
    });
</script>
<script type='text/javascript' src='jquery-1.5.1.min.js'></script>

<script type="text/javascript">
    jQuery(function($) {
        // in this scope $ refers to jQuery version 1.5.1
    });
</script>