28 2009

Discuz7和jQuery冲突的解决方法

Published by at 11:32 under JavaScript,Web技术

discuz是个好程序,但是与其他好东西的兼容性就有点差了,最近开发disczu7的辅助功能组件的时候,想用jquery,就遇到了大问题了,有时候能用,有时候不能用,我就纳闷了,于是查了一上午,发现是jquery与discuz的common.js存在兼容性冲突,头疼啊,在网上找了个解决方法,还是不错的原文如下:

Discuz和jQuery的冲突有两点,在/include/javascript/common.js文件的57~64之间有如下代码:

Array.prototype.push = function(value) {
    this[this.length] = value;
    return this.length;
}

function $(id) {
    return document.getElementById(id);
}

Discuz为了兼容低版本的IE,重写了Array对象的push方法,但在重写之前没有做任何判断,有点太XX了~,改为一下形式:

if(typeof Array.prototype.push === ‘undefined’) {
    Array.prototype.push = function(value) {
        this[this.length] = value;
        return this.length;
    }
}

第二点就是Discuz也有$()函数,就只是为了实现getElementById?功能没有人家强大就别学人家用美元符号嘛,占用符号资源。应该学学百度,人家就用一个字符G,多低调不和别人争美元。
关于$()函数的冲突,jQuery中给出了解决方法,jQuery.noConflict(),把美元让给你(看看人家多大肚)。

我们的jQuery代码可以这样写:

var jq = jQuery.noConflict(); //把$让给第一个实现它的库,用jq代替
jq(function()
{
//**********************
}
);

这样就完美解决了两者的冲突

原文:http://hi.baidu.com/mimimo/blog/item/2840768dd7048915b31bbadb.html

No responses yet

Trackback URI | Comments RSS

Leave a Reply

You must be logged in to post a comment.