用jquery如何扩展自己的插件
?
?Getting StartedTo write a jQuery plugin, start by adding a new function property to the jQuery.fn object where the name of the property is the name of your plugin:
?
?
?
The BasicsNow that we understand the context of jQuery plugins, let's write a plugin that actually does something.
?
?
(function( $ ){ var methods = { init : function( options ) { return this.each(function(){ var $this = $(this), data = $this.data('tooltip'), tooltip = $('<div />', { text : $this.attr('title') }); // If the plugin hasn't been initialized yet if ( ! data ) { /* Do more setup stuff here */ $(this).data('tooltip', { target : $this, tooltip : tooltip }); } }); }, destroy : function( ) { return this.each(function(){ var $this = $(this), data = $this.data('tooltip'); // Namespacing FTW $(window).unbind('.tooltip'); data.tooltip.remove(); $this.removeData('tooltip'); }) }, reposition : function( ) { // ... }, show : function( ) { // ... }, hide : function( ) { // ... }, update : function( content ) { // ...} }; $.fn.tooltip = function( method ) { if ( methods[method] ) { return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.tooltip' ); } };})( jQuery );??
Using data helps you keep track of variables and state across method calls from your plugin. Namespacing your data into one object literal makes it easy to access all of your plugin's properties from one central location, as well as reducing the data namespace which allows for easy removal if need be.
?
Summary and Best PracticesWriting jQuery plugins allows you to make the most out of the library and abstract your most clever and useful functions out into reusable code that can save you time and make your development even more efficient. Here's a brief summary of the post and what to keep in mind when developing your next jQuery plugin:
Always wrap your plugin in a closure:(function( $ ){ /* plugin goes here */ })( jQuery );
Don't redundantly wrap thethis
keyword in the immediate scope of your plugin's function Unless you're returning an intrinsic value from your plugin, always have your plugin's function return thethis
keyword to maintain chainability. Rather than requiring a lengthy amount of arguments, pass your plugin settings in an object literal that can be extended over the plugin's defaults. Don't clutter thejQuery.fn
object with more than one namespace per plugin. Always namespace your methods, events and data.??