jquery和prototype都是用$代替频繁的document.getElementById()操作,所以它们在一起用的必定会引起冲突,如何让jquery和prototype兼容共存呢,下面由我介绍两种方法:
第一种:先加载prototype,后加载jquery
<html> <head> <script src="/prototype.js"></script> <script src="/jquery.js"></script> <script> jQuery.noConflict(); // Put all your code in your document ready area jQuery(document).ready(function($){ // Do jQuery stuff using $ $("div").hide(); }); // Use Prototype with $(…), etc. $('someid').hide(); </script> </head> <body></body> </html>
如上所示,红色部分就是对jquery做的一个兼容处理,这样就可以达到 jquery和prototype兼容了。jQuery.noConflict();要放在 最前面,而jquery的代码就要放到 jQuery(document).ready(function($){ ……… }); 内部。
第二种:先加载jquery,后加载prototype
<html> <head> <script src="/jquery.js"></script> <script src="/prototype.js"></script> <script> // Use jQuery via jQuery(...) jQuery(document).ready(function(){ jQuery("div").hide(); }); // Use Prototype with $(...), etc. $('someid').hide(); </script> </head> <body></body> </html>
如上所示,不用调用 jQuery.noConflict();,使用 jQuery(document).ready(function(){ …….. });,在这个函数内部使用jQuery代替$。