Chu*_*ris 0 javascript jquery jquery-plugins
那么,让我们从情况开始吧.我有一个网站,Jquery 1.4.2用作Jquery的主要版本.但是用户可以使用使用其他版本(1.2.1,1.5.1等)的自定义模板.因此在某些情况下会带来冲突.
例如,这里
//included in my main view
<script type="text/javascript" src="jquery-1.4.2.min.js" ></script>
<script type="text/javascript">
$(function () {
alert($().jquery);
});
</script>
//included in custom template
<script type='text/javascript' src='jquery-1.5.1.min.js'></script>
<script type="text/javascript">
$(function () {
alert($().jquery);
});
</script>
Run Code Online (Sandbox Code Playgroud)
所以他们都警告1.5.1(因为在文档准备好时初始化).所以我想防止这种情况发生.
现在,我只有一次在我脑海中的解决方案-利用noConflict(true)和所有的改变$和Jquery符号,以新的符号在所有在我的网站使用的插件.
是否有更优雅的解决方案或我真的需要重命名我的网站中使用的所有插件?
PS另一种方式可能是使用向后兼容性插件,但在这种情况下,我需要包含许多插件,以使其与所有版本兼容.
**//included in my main view**
<script type="text/javascript" src="jquery-1.4.2.min.js" ></script>
<script type="text/javascript">
$(function () {
alert($().jquery);
});
</script>
**//included in custom template**
<script type='text/javascript' src='jquery-1.5.1.min.js'></script>
<script type="text/javascript">
$151 = jQuery.noConflict();
$151(function ($) { // In this scope $ === $151, or jQuery 1.5.1
alert($().jquery);
// $ !== jQuery.
// $().jquery = 1.5.1
// jQuery().jquery = 1.4.2
});
// outside the scope
// $ === jQuery
// $().jquery returns 1.4.2
</script>
Run Code Online (Sandbox Code Playgroud)
如何使用jQuery.noConflict();
$.noConflict() 返回jQuery的副本,你可以像这样捕获一个变量:
var j = $.noConflict()
HTML:
<script type="text/javascript" src="jquery-1.4.2.min.js" ></script>
<script type='text/javascript' src='jquery-1.5.1.min.js'></script>
Run Code Online (Sandbox Code Playgroud)
JavaScript的:
// jQuery === $
//$().jquery === 1.5.1
Run Code Online (Sandbox Code Playgroud)
.
jQ151 = $.noConflict();
Run Code Online (Sandbox Code Playgroud)
.
// jQ151 !== $
// jQ151().jquery === 1.5.1
// $().jquery === 1.4.2
Run Code Online (Sandbox Code Playgroud)
in jQuery.ready(function() {..或者只是jQuery(function() {..第一个参数是jQuery的本地副本:
<script type="text/javascript" src="jquery-1.4.2.min.js" ></script>
<script type="text/javascript">
jQuery(function($) {
// in this scope $ refers to jQuery version 1.4.2
});
</script>
<script type='text/javascript' src='jquery-1.5.1.min.js'></script>
<script type="text/javascript">
jQuery(function($) {
// in this scope $ refers to jQuery version 1.5.1
});
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
819 次 |
| 最近记录: |