I've been working with JQuery for some time now and I've always used the following to initalise my javascript:
$(document).rea开发者_开发问答dy( function() {
// Initalisation logic
});
However, recently I've noticed a lot of examples using the following:
$(function() {
});
Whats the difference?
Thanks
Basically, there isn't one. The $(...) format is a shortcut. See the API docs for jQuery() for details.
I like to use it like this:
jQuery(function($) {
// ...all of my jQuery-specific code here...
});
...because then if I need to, I can use noConflict if I end up having to mix something into the page that also wants the $ symbol, but I can still use $ in my code (because jQuery passes itself into the callback as the first argument, and as you can see I'm accepting that argument as $ in my callback function — and so that shadows any global $ symbol that another library might be using). The above also has the advantage that I can have symbols global to my code (vars within the anonymous function) that are not actually globals.
The difference is a matter of style. One is just a shortcut of the other. :) See http://api.jquery.com/jQuery/ near the bottom where it says "Executes the function when the DOM is ready to be used"
When I asked one of the jQuery UI people what they preferred, he said he preferred the more verbose way. However, people in my shop use this version:
$(function() {
});
The difference is that the first is more readable. So please just use this one.
$(document).ready(function() {
// Initalisation logic
});
加载中,请稍侯......
精彩评论