您的位置:首页 > Web前端 > JQuery

jQuery基础学习3——jQuery库冲突

2015-09-03 16:41 761 查看
默认情况下,jQuery用$作为自身的快捷方式。

jQuery库在其他库之后导入

在其他库和jQuery库都被加载完毕后,可以在任何时候调用jQuery.noConflict()函数来将变量$的控制权移交给其他JavaScript库。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>冲突解决1</title>
<!-- 引入 prototype  -->
<script src="lib/prototype.js" type="text/javascript"></script>
<!-- 引入 jQuery  -->
<script src="../../scripts/jquery.js" type="text/javascript"></script>
</head>
<body>
<p id="pp">Test-prototype(将被隐藏)</p>
<p >Test-jQuery(将被绑定单击事件)</p>
<script type="text/javascript">
jQuery.noConflict();                //将变量$的控制权让渡给prototype.js
jQuery(function(){                    //使用jQuery
jQuery("p").click(function(){
alert( jQuery(this).text() );
});
});

$("pp").style.display = 'none';        //使用prototype.js隐藏元素
</script>
</body>
</html>


可以在程序里将jQuery()函数作为jQuery对象的制造工厂。

如果想确保jQuery不会与其他库冲突,但又想自定义一个快捷方式,可以使用如下的操作:

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

$("pp").style.display = 'none';        //使用prototype.js隐藏元素


如果不想给jQuery自定义备用名称,还想使用$而不管其他库的$()方法,同时又不想与其他库相冲突,那么可以使用下面的解决方法:

jQuery.noConflict();                //将变量$的控制权让渡给prototype.js
jQuery(function($){                    //使用jQuery设定页面加载时执行的函数,重点是把$作为参数传递给了函数
$("p").click(function(){        //继续使用 $ 方法
alert( $(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


jQuery库在其他库之前导入

如果jQuery库在其他库之前就导入了,那么可以直接使用“jQuery”来做一些jQuery的工作,同时可以使用$()方法作为其他库的快捷方式,这里无须调用jQuery.onConflict()函数。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>冲突解决5</title>
<!-- 引入 jQuery  -->
<script src="../../scripts/jquery.js" type="text/javascript"></script>
<!-- 引入 prototype  -->
<script src="lib/prototype.js" type="text/javascript"></script>
</head>
<body>
<p id="pp">Test-prototype(将被隐藏)</p>
<p >Test-jQuery(将被绑定单击事件)</p>

<script type="text/javascript">
jQuery(function(){   //直接使用 jQuery ,没有必要调用"jQuery.noConflict()"函数。
jQuery("p").click(function(){
alert( jQuery(this).text() );
});
});

$("pp").style.display = 'none'; //使用prototype
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: