jQuery 名称冲突

jQuery 名称冲突

jQuery 使用 $ 符号作为 jQuery 的简介方式。

某些其他 JavaScript 库中的函数(比如 Prototype)同样使用 $ 符号,这样一起使用时就会起冲突!解决办法如下。

一、使用jquery中的jQuery.noConflict();
 
方法即可把变量$的控制权让渡给第一个实现它的那个库或之前自定义的$方法。
之后应用Jquery的时候只要将所有的$换成jQuery即可,如原来引用对象方法$("#msg")改为jQuery("#msg")。
如:
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
jQuery.noConflict();//开始使用jQuery(默认名)
jQuery(document).ready(function(){
  jQuery("button").click(function(){
    jQuery("p").hide();
  });
});
</script>
</head>

<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button type="button">Click me</button>
</body>
</html>
 
二、自定义jQuery使用符号
 
同样用到jQuery 使用名为 noConflict() 的方法来解决该问题。
var jq=jQuery.noConflict(),帮助您使用自己的名称(比如 jq)来代替 $ 符号。
 
如:
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
var jq=jQuery.noConflict();
jq(document).ready(function(){
  jq("button").click(function(){
    jq("p").hide();
  });
});
</script>
</head>

<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button type="button">Click me</button>
</body>
</html>
原文地址:https://www.cnblogs.com/svennee/p/4072997.html