version 1:
function add(){
var a = 2;
...
...
...
}
version 2:
$(function(){
var ...
..
..
});
Where is the main difference of two versions? For version 2, it does not have the function name. If it just simply run the code in the function, why not just remove the $function(){..};. It really makes me confusing because nowadays, many scripts are written in style of version 2. Please help to clarify my confusion.
Example 1 is defining a function called
add, whereas example 2 is simply passing an anonymous function to the jQuery function.The
$(function() {...});syntax is a shorthand for$(document).ready(function() {...});, which takes a function as its argument, and then executes that function when the DOM is ready. This is used to ensure that elements you want to work with in your Javascript actually exist before executing the code.Edit to address the comment below:
The
.click()jQuery function has two uses. If you pass a function then it creates an additional click event handler, which will run that function when the event is triggered. If you don’t pass a function, then it will trigger all click event handlers that have been attached to the element(s) in the jQuery object. So, yes, you can call.click()without a function, but it doesn’t do the same thing.You can’t do the following:
because that will give you a syntax error. You can, however, define a function in the usual fashion, then pass that to the call to
$(document).ready():