jQuery 使用注意事项 与 小技巧(tips)
1
$( document ).ready()
https://learn.jquery.com/using-jquery-core/document-ready/
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside
$( document ).ready()
will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside$( window ).load(function() { ... })
will run once the entire page (images or iframes), not just the DOM, is ready.
1234// A $( document ).ready() block.
$( document ).ready(function() {
console.log( "ready!" );
});
Experienced developers sometimes use the shorthand
$()
for$( document ).ready()
. If you are writing code that people who aren't experienced with jQuery may see, it's best to use the long form.
1234// Shorthand for $( document ).ready()
$(function() {
console.log( "ready!" );
});
You can also pass a named function to
$( document ).ready()
instead of passing an anonymous function.
123456789// Passing a named function instead of an anonymous function.
function readyFn( jQuery ) {
// Code to run when the document is ready.
}
$( document ).ready( readyFn );
// or:
$( window ).load( readyFn );
The example below shows
$( document ).ready()
and$( window ).load()
in action. The code tries to load a website URL in an<iframe>
and checks for both events:
1234567891011121314151617<html>
<head>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
console.log( "document loaded" );
});
$( window ).load(function() {
console.log( "window loaded" );
});
</script>
</head>
<body>
<iframe src="http://techcrunch.com"></iframe>
</body>
</html>
1
$ 符号与其他框架的混合使用,产生的冲突的避免方式:
《1》jQuery 在其他库之后导入
method: 1
//将变量$的控制权,让渡给prototype.js(一种js框架) jQuery.noConflict(); //使用 jQuery(), 代替$()方法 jQuery(function(){ //do some things });method: 2
// 自定义一个快捷方式: var $x = jQuery.noConflict(); $x (function(){ //do some things //函数内部使用$x()方法,代替$()方法 })method: 3
method: 4//将变量$的控制权,让渡给prototype.js(一种js框架) jQuery.noConflict(); //使用 jQuery设置页面加载时的执行函数 jQuery(function($){ //do some things //函数内部正常使用$()方法 });/* 最理想的方式,通过改变少量的代码,实现最全面的兼容性! */ //将变量$的控制权,让渡给prototype.js(一种js框架) jQuery.noConflict(); //定义匿名函数,并设置形参为$ //匿名函数内部的$ == jQuery (function($){ $(function(){ //do some things //可以正常使用$()方法 }); })(jQuery); //执行匿名函数,且传递实参jQuery《2》jQuery 在其他库之前导入
method: 5
//不需要调用jQuery.noConflict(); //可以使用$()方法作为其他框架/库的快捷方式 //直接使用 jQuery(), 代替$()方法 jQuery(function(){ //do some things //使用 jQuery(), 代替$()方法 });
1
1