1

我用

<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();在上面的脚本中使用以防止冲突

4

2 回答 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 和 mootools 都使用的对象jQuery$由于您同时使用两者,您应该将所有 jQuery 代码包装在这样的闭包中(每个 .js 文件或script标签一个)。

于 2009-10-25T22:56:23.713 回答
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 放弃$()。您在问题中的代码已经做了另一件方便的事情,即使用就绪事件处理程序的参数作为在本地使用jQuery对象的较短名称的一种方式。

我强烈建议阅读有关使用其他库的 jQuery 页面noConflict()以及该函数的文档。

于 2009-10-26T02:33:57.877 回答