js冲突怎么解决?

2025-02-23 13:07:40
推荐回答(1个)
回答1:

jQuery多个版本或和其他js库冲突主要是常用的$符号的问题,主要解决办法如下:

方法一:

jQuery.noConflict(); //将变量$的控制权让渡给prototype.jsjQuery(function(){ //使用jQueryjQuery("p").click(function(){
alert( jQuery(this).text() );
});
});
$("pp").style.display = 'none'; //使用prototype

方法二:

var $j = jQuery.noConflict(); //自定义一个比较短快捷方式$j(function(){ //使用jQuery$j("p").click(function(){
alert( $j(this).text() );
});
});
$("pp").style.display = 'none'; //使用prototype

方法三:

jQuery.noConflict(); //将变量$的控制权让渡给prototype.js(function($){ //定义匿名函数并设置形参为$$(function(){ //匿名函数内部的$均为jQuery$("p").click(function(){ //继续使用 $ 方法alert($(this).text());
});
});
})(jQuery); //执行匿名函数且传递实参jQuery$("pp").style.display = 'none'; //使用prototype