五种方法解决jQuery和Prototype兼容性

第一种状况:先加载Prototype,再加载jQuery

方法一:jQuery 库和它的全部插件都是在jQuery名字空间内的,包括全局变量也是保存在jQuery 名字空间内的。

使用jQuery.noConflict();主要做用是在任什么时候候,只要在jQuery加载后就能够调用,将$符号的使用权返回给其它的js库,jQuery在建立它本身的名字空间时就将其它库的$保存在本身的一个变量当中。 javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<html>
<head>
  <scriptsrc="prototype.js"></script>
  <scriptsrc="jquery.js"></script>
  <scripttype="text/javascript">
     //各个js库之间的主要冲突在于$的冲突,这个方法是用来处理这个问题的
     jQuery.noConflict(); 
 
     //本来使用jQuery代码部分的$ 用jQuery替代
     jQuery(document).ready(function (){
       jQuery("div").hide();
     });
 
     // Use Prototype with $(...), etc.
     $('proto').hide();
  </script>
</head>
<body></body>
</html>

方法二:若是你仍然想使用相似于$这样比较简短的字符,你能够将jQuery.noConflict()的返回值赋值给某个变量。这个变量就是jQuery的新缩写了,固然你可使用$之外的任意字符串,好比:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<html>
<head>
  <scriptsrc="prototype.js"></script>
  <scriptsrc="jquery.js"></script>
  <scripttype="text/javascript">
     //$j就至关于jQuery,名称你能够自主定义
     var  $j = jQuery.noConflict(); 
 
     // Use jQuery via $j(...)
     $j(document).ready(function (){
       $j("div").hide();
     }); 
 
     // Use Prototype with $(...), etc.
     $('proto').hide();
  </script>
</head>
<body></body>
</html>

方法三:若是你仍是想使用$,而不想使用别的字符,也是能够的。并且一般程序员都比较喜欢这样作,由于这样作写好的代码几乎都不用替换原来的$符号。那就是利用名字空间的概念就全部的jQuery代码封装在document的ready事件名字空间范围内,如:jQuery(document).ready(这里填入jQuery代码),Magento笔记喜欢使用这种方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<html>
<head>
  <scriptsrc="prototype.js"></script>
  <scriptsrc="jquery.js"></script>
  <scripttype="text/javascript">
    jQuery.noConflict(); 
 
    // Put all your code in your document ready area
    jQuery(document).ready(function ($){
      // 这样你能够在这个范围内随意使用$而不用担忧冲突
      $("div" ).hide();
    }); 
 
    // Use Prototype with $(...), etc.
    $('proto' ).hide();
  </script>
</head>
<body></body>
</html>

第二种状况:先加载jQuery,再加载Prototype

按照这样的顺序加载,就不存在其它js库的$符号被jQuery占用的问题。因此对其它的js库的代码能够不做任何修改,照常使用$,而对 jQuery可使用jQuery来替代$.如: html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<html>
<head>
  <scriptsrc="prototype.js"></script>
  <scriptsrc="jquery.js"></script>
  <scripttype="text/javascript">
  // 使用 jQuery 用 jQuery(...)
  jQuery(document).ready(function (){
    jQuery("div" ).hide();
  }); 
 
  // 使用 Prototype 时,用 $(...),
  $('someid' ).hide();
  </script>
</head>
<body></body>
</html>

或者你不想写jQuery这么长的字符,你能够经过另一种方法: java

1
var  $j = jQuery;

来实现简短一点的$j,这多是最好的办法了。
不过,当你只想使用jQuery来写代码时,你能够经过名字空间仍然使用$,即采用和jQuery源代码同样的方法: jquery

1
2
3
4
5
6
<scripttype="text/javascript">
    (function($) {
    /* 在这个名字空间内,你能够随意使用$符号来引用jQuery,只不过是其它$被jQuery使用,你不能使用prototype或其它的js库
    */ }
    )(jQuery)
</script>

参考来源:http://docs.jquery.com/Using_jQuery_with_Other_Libraries 程序员

相关文章
相关标签/搜索