jQuery - 使用要点 - 避免同其他JavaScript库的冲突

避免同其他JavaScript库的冲突

默认情况下,jQuery使用$符号作为jQuery的简写形式;若同时使用的其他JavaScript库中,使用$变量,此时就会痛jQuery发生冲突。避免冲突的方式:

将jQuery置于无冲突模式

使用另外的变量,代替$别名。

<!-- Putting jQuery into no-conflict mode. -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
 
var $j = jQuery.noConflict();
// $j is now an alias to the jQuery function; creating the new alias is optional.
 
$j(document).ready(function() {
    $j( "div" ).hide();
});
 
// The $ variable now has the prototype meaning, which is a shortcut for
// document.getElementById(). mainDiv below is a DOM element, not a jQuery object.
window.onload = function() {
    var mainDiv = $( "main" );
}
 
</script>
<!-- Another way to put jQuery into no-conflict mode. -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
 
jQuery.noConflict();
 
jQuery( document ).ready(function( $ ) {
    // You can use the locally-scoped $ in here as an alias to jQuery.
    $( "div" ).hide();
});
 
// The $ variable in the global scope has the prototype.js meaning.
window.onload = function(){
    var mainDiv = $( "main" );
}
 
</script>

在其他库之前加载jQuery库

<!-- Loading jQuery before other libraries. -->
<script src="jquery.js"></script>
<script src="prototype.js"></script>
<script>
 
// Use full jQuery function name to reference jQuery.
jQuery( document ).ready(function() {
    jQuery( "div" ).hide();
});
 
// Use the $ variable as defined in prototype.js
window.onload = function() {
    var mainDiv = $( "main" );
};
 
</script>

引用jQuery函数的方式概述

创建新别名 jQuery.noConflict()方法会返回对jQuery函数的引用

<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
 
// Give $ back to prototype.js; create new alias to jQuery.
var $jq = jQuery.noConflict();
 
</script>

使用立即调用函数表达式

<!-- Using the $ inside an immediately-invoked function expression. -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
 
jQuery.noConflict();
 
(function( $ ) {
    // Your jQuery code here, using the $
})( jQuery );
 
</script>

若是用这种方式,在立即执行函数表达式中,无法使用prototype.js中的方法。

使用传递给$(document).ready()函数的参数

<script src="jquery.js"></script>
<script src="prototype.js"></script>
<script>
 
jQuery(document).ready(function( $ ) {
    // Your jQuery code here, using $ to refer to jQuery.
});
 
</script>

// 简明模式
<script src="jquery.js"></script>
<script src="prototype.js"></script>
<script>
 
jQuery(function($){
    // Your jQuery code here, using the $
});
 
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值