一:在其他库和jQuery库都被加载完毕后,可以在任何时候调用jQuery.noConflict()函数来将变量$的控制权移交给其他Javascript库。
jQuery在其他加载之后:
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="../prototype.js"></script>
<script type="text/javascript" src="../jquery-1.9.1.js"></script>
<title>无标题文档</title>
</head>
<body>
<p>使用jQuery</p>
<p id="pp">使用prototype.js隐藏元素</p>
<script language="javascript">
jQuery.noConflict();//将变量$的控制权移交给prototype.js
jQuery(function(){
jQuery("p").click(function(){//使用jQuery
alert(jQuery(this).text());
});
});
$("pp").style.display = 'none';//使用prototype.js隐藏元素
</script>
</body>
</html>
二、也可以自定义一个快捷方式:
<script language="javascript">
var $j = jQuery.noConflict(); //自定义一个快捷方式
$j(function(){ //使用jQuery,利用自定义快捷方式----$j
$j("p").click(function(){//使用jQuery
alert($j(this).text());
});
});
$("pp").style.display = 'none';//使用prototype隐藏元素
</script>
三、在函数内部继续使用$()方法:
<scriptlanguage="javascript">
jQuery.noConflict(); //将变量$的控制权移交给prototype.js
(function($){ //定义匿名函数并设置形参为$
$(function(){ //匿名函数的内部均为jQuery
$("p").click(function(){ //在函数内部继续使用$()方法
alert($(this).text());
});
});
})(jQuery); //执行匿名函数且传递实参jQuery
$("pp").style.display = 'none';//使用prototype隐藏元素
</script>
四、定义匿名函数:
<script language="javascript">
jQuery.noConflict(); //将变量$的控制权移交给prototype.js
(function($){ //定义匿名函数并设置形参为$
$(function(){ //匿名函数的内部均为jQuery
$("p").click(function(){ //在函数内部继续使用$()方法
alert($(this).text());
});
});
})(jQuery); //执行匿名函数且传递实参jQuery
$("pp").style.display = 'none';//使用prototype隐藏元素
</script>
五、jQuery在其他库加载之前:
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="../jquery-1.9.1.js"></script>
<script type="text/javascript" src="../prototype.js"></script>
<title>无标题文档</title>
</head>
<body>
<p>使用jQuery</p>
<p id="pp">使用prototype.js隐藏元素</p>
<script language="javascript">
//jQuery.noConflict();//无需将变量$的控制权移交给prototype.js
jQuery(function(){ //直接使用jQuery
jQuery("p").click(function(){//使用jQuery
alert(jQuery(this).text());
});
});
$("pp").style.display = 'none';//使用prototype.js隐藏元素
</script>
</body>
</html>