Basic points of the plugin:
1. Name recommendation: jquery. [Plugin name].js, avoid confusion with other JS library plugins.
2. Object method attached to: Jquery.fn, global function attached to: JQuery object itself.
3. Inside the plug-in, this points to the JQuery object currently acquired through the selector, not a DOM object.
4. If the selector gets multiple elements, it can be traversed by This.each.
5. Plug-ins should return jquery objects for easy chain operation.
6. Avoid using the $ alias inside the plugin, which should be expressed in full jquery. Closures can be used to avoid this problem.
// for better compatibility, add a semicolon to prevent compression when the other JS code does not have a semicolon ;(function($) { // here will be the parameters of the anonymous function passed in // write Code }) (jQuery); // jquery is passed in as an argument and can be used within an anonymous function.
The closure in the plugin understands:
;(function($){ varfoo = 1;//define local variables, only the anonymous function can be accessed internally varBar =function(){ /*The function inside the anonymous function can access Foo, even if the bar function is called outside of the anonymous function, it can be accessed inside bar (), but it cannot be accessed directly outside of the anonymous function .*/ } /*the functions below allow the function bar () inside the anonymous function to escape to the globally accessible range so that the internally defined function bar () can be accessed outside of the anonymous function, and the internal function bar () can also access the Foo variable .*/ $. BAR=bar ();}) (jQuery);
Sharp jquery-7--Writing plug-in basics