jQuery核心之 $

时间:2023-03-09 16:48:49
jQuery核心之 $
参考jQuery官网API文档
$ 和 $() 的区别很重要:

1、$(document).ready() 和 $(document).load() 的 区别:

    前者等到DOM准备好了之后就会触发,后者必须等到整个网页(包括图片,iframe)准备好了才触发。

    $(function(){
        alert("hello jquery");
    }); 是 $(document).ready(function(){
        alert("hello jquery");
    })的缩写。

2、$ 即 为 jQuery的缩写,但是其他的框架可能也用 $ 来表示一些变量(并且在jquery之前加载),这个时候要避免这些冲突:
    var $j = jQuery.noConflict();    
    现在  $j 代表了之前的 $.

或者将  $ 以参数的形式传递在ready函数中传递:
<!-- 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>

 
总之有以下几种方法:
方法一,创建一个新的别名代替$
<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> 

方法二、使用一个可以立即触发的函数表达式(将jQuery通过参数的形式传递给匿名函数):
例如:
<!-- 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> 

方法三、在jQuery( 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>