Home > Article > Web Front-end > Two solutions to jQuery prototype conflicts (with demo sample download)_jquery
This article analyzes two solutions to jQuery prototype conflicts with examples. Share it with everyone for your reference, the details are as follows:
How can jquery and prototype conflict? In the final analysis, it is because both of them use $, and they are used at the same time, which is confusing. This problem has been solved no less than 5 times, and I have to check it every time. It doesn't hurt, hehe.
Method 1. Add code to the core library file of jquery.
1. It is usually jquery.js, or jquery.min.js, some with version numbers. Just know which file it is.
})( window ); jQuery.noConflict(); //最后面,加上这一行。
2. Load test jquery and prototype files
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"></script> <script src="jquery.min.js"></script>
3. How to write js code
<script type="text/javascript"> alert('prototype value : '+$('test').value); //prototype写法 jQuery(document).ready(function($){ //注意这里的,jQuery和$ alert('jquery value : '+$('#test').val()); //jquery写法 }); </script>
Recommended this method, this method is more effective once and for all
The complete demo code is as follows:
<html> <head> <script type="text/javascript" src="./prototype.js"></script> <script src="jquery.min.js"></script> </head> <body> <form> <input id="test" type='text' name='test' value='test'/> </form> <script type="text/javascript"> alert('prototype value : '+$('test').value); jQuery(document).ready(function($){ alert('jquery value : '+$('#test').val()); }); </script> </body> </html>
Method 2: Resolve the conflict where jquery is called
1. Load test jquery and prototype files
//jquery和prototype,没有先后顺序,谁先谁后都一样。 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"></script>
2. js code
<script type="text/javascript"> jQuery.noConflict(); //解决冲突,这个一定要放在js代码的最前面,不然就会报错了。 alert('prototype value : '+$('test').value); jQuery(document).ready(function($){ alert('jquery value : '+$('#test').val()); }); </script>
This method is more suitable for situations where the core source files of jquery are not on your own server, or the jquery code is relatively small. The sample demoClick here to view.
The complete demo can be clicked hereDownload from this site.
I hope this article will be helpful to everyone in jQuery programming.