开发者

Why do I have to place my entire code in $(function(){/* code goes here */});?

So I understand that if I have to place this code

$("#MyButton").click(function(){/* code goes here */});

in an external .js file, I have to reference the script

<script src="MyScript.js" type="text/javascript"></script>
</body>

just before closing the body tag (and not in head) otherwise it doesn't work because the DOM has to be fully loaded before MyScript.js

BUT includin开发者_如何学Pythong my entire code in

$(function(){
    $("#MyButton").click(function(){/* code goes here */});
});

somehow makes it all work EVEN THOUGH I place the script now in HEAD (instead of just before closing body tag, like earlier)!!

How come??


Because $(f) is shortcut for "execute function f when dom is ready"


$(function(){ });

is an equivalent of

$(document).ready(function(){ });

So it will be fired when the DOM is loaded. More informations here.


JS executes the moment it's encountered by the browser. If you put your script in the head block, the #Mybutton you want has not yet been loaded. As far as your script is conerned, #MyButton doesn't exist.

But when you do the $(function())... version, it tells JQuery to define the function, but NOT EXECUTE UNTIL the entire page DOM has been loaded. At that point, #MyButton is present and the script will execute as expected.

In real world terms, you're trying to make a sandwich before the bread's finished baking. By using that special notation, you wait until the bread comes out of the oven before starting to spread the butter and mustard.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜