您的位置:首页 > Web前端 > JQuery

$( document ).ready()

2015-11-23 13:10 591 查看
Apagecan'tbemanipulatedsafelyuntilthedocumentis"ready."jQuerydetectsthisstateofreadinessforyou.Codeincludedinside 
$(
document).ready()
 willonlyrunoncethepageDocumentObjectModel(DOM)isreadyforJavaScriptcodetoexecute.Codeincludedinside 
$(
window).load(function(){...})
 willrunoncetheentirepage(imagesoriframes),notjusttheDOM,isready.

1

2

3

4
//A$(document).ready()block.
$(document).ready(function(){
console.log("ready!");
});

Experienceddeveloperssometimesusetheshorthand 
$()
 for 
$(
document).ready()
.Ifyouarewritingcodethatpeoplewhoaren'texperiencedwithjQuerymaysee,it'sbesttousethelongform.

1

2

3

4
//Shorthandfor$(document).ready()
$(function(){
console.log("ready!");
});

Youcanalsopassanamedfunctionto 
$(document).ready()
 insteadofpassingananonymous
function.

1

2

3

4

5

6

7

8

9
//Passinganamedfunctioninsteadofananonymousfunction.
functionreadyFn(jQuery){
//Codetorunwhenthedocumentisready.
}
$(document).ready(readyFn);
//or:
$(window).load(readyFn);

Theexamplebelowshows 
$(document).ready()
 and 
$(
window).load()
 inaction.ThecodetriestoloadawebsiteURLinan 
<iframe>
 and
checksforbothevents:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17
<html>
<head>
<scriptsrc="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(){
console.log("documentloaded");
});
$(window).load(function(){
console.log("windowloaded");
});
</script>
</head>
<body>
<iframesrc="http://techcrunch.com"></iframe>
</body>
</html>

https://learn.jquery.com/using-jquery-core/document-ready/ 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jquery