zoukankan      html  css  js  c++  java
  • 锋利的jQuery-1--解决jquery库和其他库的冲突

    在jquery中,$(美元符号)就是jquery的别名,也就是说使用$和使用jquery是一样的,在很多时候我们命名空间时,正是因为这 个$而产生的冲突的发生。比如说:$('#xmlas')和JQuery('#xmlas') 虽然在写法上不同,但在实际上却是完全等同的。

    要想解决这个冲突,其实最简单的方法就是使用不同的名称来命名,或者让执行代码认为是不同的命名空间即可。

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

    1.使用jQuery代替$

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

    2.定义$的别名

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

    3.使用jquery自动加载的方式

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

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

    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <!--先导入jQuery -->
    <script src="../../scripts/jquery-1.3.1.js" type="text/javascript"></script>
    <!--后导入其他库 -->
    <script src="prototype-1.6.0.3.js" type="text/javascript"></script>
    </head>
    <body>
    <p id="pp">test---prototype 
    <p >test---jQuery   
     <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>
     
  • 相关阅读:
    人机交互设计 课后作业--评价正在使用的输入法
    站立会议10--个人总结
    站立会议09--个人总结
    08个人总结
    站立会议07--个人总结
    站立会议06--个人总结
    站立会议05--个人总结
    软件工程概论-合作作业01
    软件工程概论-个人作业04
    学习进度(第四周)
  • 原文地址:https://www.cnblogs.com/leezhxing/p/4041085.html
Copyright © 2011-2022 走看看