如何解决jQuery和mootools冲突?

问题描述 投票:1回答:2

我用

<script type="text/javascript" src="jquery-1.2.2.pack.js"> </script> 

加载jquery,然后加载包含以下内容的外部脚本:


var jkpanel={
    controltext: 'menu',
    $mainpanel: null, contentdivheight: 0,
    openclose:function($, speed){
    this.$mainpanel.stop() //stop any animation
    if (this.$mainpanel.attr('openstate')=='closed')
        this.$mainpanel.animate({top: 0}, speed).attr({openstate: 'open'})
    else
        this.$mainpanel.animate({top: -this.contentdivheight+'px'}, speed).attr({openstate: 'closed'})
},

init:function(file, height, speed){
    jQuery(document).ready(function($){
        jkpanel.$mainpanel=$('<div id="dropdownpanel"><div class="contentdiv"></div><div class="control">'+jkpanel.controltext+'</div></div>').prependTo('body')
        var $contentdiv=jkpanel.$mainpanel.find('.contentdiv')
        var $controldiv=jkpanel.$mainpanel.find('.control').css({cursor: 'wait'})
        $contentdiv.load(file, '', function($){
                var heightattr=isNaN(parseInt(height))? 'auto' : parseInt(height)+'px'
                $contentdiv.css({height: heightattr})
                jkpanel.contentdivheight=parseInt($contentdiv.get(0).offsetHeight)
                jkpanel.$mainpanel.css({top:-jkpanel.contentdivheight+'px', visibility:'visible'}).attr('openstate', 'closed')
                $controldiv.css({cursor:'hand', cursor:'pointer'})
        })
        jkpanel.$mainpanel.click(function(){jkpanel.openclose($, speed)})       
    })
}
}

//Initialize script: jkpanel.init('path_to_content_file', 'height of content DIV in px', animation_duration)
jkpanel.init('1', '80px', 1000)

当然也使用mootools插件。

我的问题是我应该如何在上面的脚本中使用var $j = jQuery.noConflict();来防止冲突

javascript jquery plugins mootools conflict
2个回答
5
投票

将所有依赖于jQuery的JavaScript包装在一个闭包中以防止命名空间冲突,如下所示:

// Start closure to prevent namespace conflicts
;(function($) {

  // Whatever code you want that relies on $ as the jQuery object

// End closure
})(jQuery);

它看起来很奇怪,但语法是正确的(是的,第一行以分号开头)。这会自动将jQuery替换为$对象,jQuery和mootools都使用它。既然你正在使用它们,你应该将所有jQuery代码包装在一个这样的闭包中(每个.js文件或script标签一个)。


2
投票

如果问题是正确的,你加载MooTools,然后你加载jQuery,然后MooTools不起作用,因为jQuery接管了美元函数,那么你可能只需要这样的代码:

<script type="text/javascript" src="mootools.js"> </script>
<script type="text/javascript" src="jquery-1.2.2.pack.js"> </script>
<script type="text/javascript">
  jQuery.noConflict();
</script>

这应该让jQuery放弃$()。您在问题中的代码已经做了另一个方便的事情,即使用参数到ready事件处理程序作为本地使用jQuery对象的较短名称的方法。

我强烈建议阅读jQuery page on working with other libraries以及noConflict()函数的文档。

© www.soinside.com 2019 - 2024. All rights reserved.