jquery库与其他库冲突的解决方法

 
更多

在使用jQuery开发的时候,可能还会使用到其他的JS库或插件,比如Prototype,但多库共存时可能会发生冲突导致发生各种意外。下面就和大家分享几种jquery库与其他库发生冲突时的解决方法。

一、 jQuery库在其他库之前导入,直接使用jQuery(callback)方法如:

<html xmlns="http://www.phpernote.com/php-function/849.html">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jquery库与prototype库冲突的解决方法</title>
<!--先导入jQuery -->
<script type="text/javascript" src="http://www.phpernote.com/js/jquery.min.js"></script>
<!--后导入其他库 -->
<script type="text/javascript" src="http://www.phpernote.com/js/prototype-1.6.0.3.js"></script>
</head>
<body>
<p>这是一篇关于如何解决jquery库与prototype库冲突的方法分享</p>
<script type="text/javascript">
jQuery(function(){ //直接使用 jQuery ,没有必要调用"jQuery.noConflict()"函数。
	jQuery("p").click(function(){ 
		   alert( jQuery(this).text() );
	});
});
$("p").style.display='none'; //使用prototype
</script>
</body>
</html>

二、jQuery库在其他库之后导入,使用jQuery.noConflict()方法将变量$的控制权让渡给其他库,有以下几种方式:

(1)方法一

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

(2)方法二

<script type="text/javascript">
jQuery.noConflict(); //将变量$的控制权让渡给prototype.js
	jQuery(function($){ //使用jQuery
	$("p").click(function(){ //继续使用 $ 方法
		alert( $(this).text() );
	});
});
$("p").style.display = 'none'; //使用prototype
</script>

(3)方法三

<script type="text/javascript">
jQuery.noConflict(); //将变量$的控制权让渡给prototype.js
(function($){ //定义匿名函数并设置形参为$
	$(function(){ //匿名函数内部的$均为jQuery
		$("p").click(function(){ //继续使用 $ 方法
			alert($(this).text());
		});
	});
})(jQuery); //执行匿名函数且传递实参jQuery
$("p").style.display = 'none'; //使用prototype
/*********************************************************************/
jQuery(document).ready(function(){ //一加载页面的时候就将权利让出去 
	jQuery.noConflict(); 
});
</script>
打赏

本文固定链接: https://www.cxy163.net/archives/3994 | 绝缘体

该日志由 绝缘体.. 于 2013年06月20日 发表在 未分类 分类下, 你可以发表评论,并在保留原文地址及作者的情况下引用到你的网站或博客。
原创文章转载请注明: jquery库与其他库冲突的解决方法 | 绝缘体
关键字: , , , ,

jquery库与其他库冲突的解决方法:等您坐沙发呢!

发表评论


快捷键:Ctrl+Enter