Share some experiences gained when developing jQuery plug-ins.
1. Watch first
jQuery(function(){ });
Written in full as
jQuery(document).ready(function(){ });
The meaning is that the ready() method is executed after the DOM is loaded.
2. Watch again
(function(){ })(jQuery);
It actually executes the ()(para) anonymous method, but just passes the jQuery object.
(function($) {…})(jQuery);
This is actually an anonymous function, as follows:
function(arg){…}
This defines an anonymous function with the parameter arg
When calling a function, parentheses and actual parameters are written after the function. Due to the priority of the operator, the function itself also needs parentheses, that is:
(function(arg){…})(param)
This is equivalent to defining an anonymous function with parameter arg, and calling this anonymous function using param as a parameter
(function($){…})(jQuery) is the same. The reason why $ is only used in formal parameters is to avoid conflict with other libraries, so jQuery is used for actual parameters
Equivalent to function output(s){…};output(jQuery); or var fn=function(s){…};fn(jQuery);
$(function(){…});
or:
jQuery(function($) {
…
});
Allows you to bind a function that will be executed after the DOM (excluding images) document is loaded. This function works the same as $(document).ready(), except that when using this function, you need to wrap all the $() operators in the page that need to be executed when the DOM is loaded. Technically, this function is chainable - but not many cases actually link in this way.
The full form of is:
$(document).ready(function(){
…
});
3. Summary
jQuery(function(){}); is used to store code that operates DOM objects. The DOM object already exists when the code is executed. It cannot be used to store code for developing plug-ins, because the jQuery object is not passed, and its methods (functions) cannot be called externally through jQuery.method.
(function(){})(jQuery); is used to store the code for developing plug-ins. The DOM may not exist when the code is executed, so please use the code that directly automatically performs DOM operations with caution.