jQuery库与其他JS库冲突的解决办法

关键字: javascript
现在的js库很多,而且各有所长。像我,就比较喜欢jQuery,但同时也会使用一下其他的js库,如YUI,DWR什么的。但是它们却时不时地相互闹些小矛盾,真是让人头痛。究其原因,原来是它们的全局对象定义冲突了,特别是变量”$”,几乎百分之百要在这中招。怎么办?呵呵,看我的!

重载$函数。使用jQuery.noConflict()就可以通过重载$函数,从而区分开跟其他js库的重叠部分。例子如下:

Js代码
<script src="prototype.js"></script>  
<script src="<SPAN class=hilite1>jquery</SPAN>.js"></script>  
<script>  
    <SPAN class=hilite1>jQuery</SPAN>.noConflict();  
 
    // Use <SPAN class=hilite1>jQuery</SPAN> via <SPAN class=hilite1>jQuery</SPAN>(…)  
    <SPAN class=hilite1>jQuery</SPAN>(document).ready(function(){  
    <SPAN class=hilite1>jQuery</SPAN>(”div”).hide();  
    });  
 
    // Use Prototype with $(…), etc.  
    $(’someid’).style.display = ‘none’;  
</script> 

<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
    jQuery.noConflict();

    // Use jQuery via jQuery(…)
    jQuery(document).ready(function(){
    jQuery(”div”).hide();
    });

    // Use Prototype with $(…), etc.
    $(’someid’).style.display = ‘none’;
</script>
记得要在载入完各js库后才能用jQuery.noConflict()进行重载哦,如例子中的prototype和jquery。

当然我们也可以不使用其默认的名字空间,比如我喜欢使用 $j() 而不是 jQuery() 。

Js代码
var $j = <SPAN class=hilite1>jQuery</SPAN>.noConflict();  
$j(document).ready(function(){  
    $j(”div”).hide();  
}); 

var $j = jQuery.noConflict();
$j(document).ready(function(){
    $j(”div”).hide();
});
呵呵,很简单吧。原文在这里http://docs.jquery.com/Using_jQuery_with_Other_Libraries

你可能感兴趣的:(jquery,DWR,prototype,J#,yui)