(function ( $ ) { $.fn.greenify = function( options ) { // This is the easiest way to have default options. var settings = $.extend({ // These are the defaults. color: "#556b2f", backgroundColor: "white" }, options ); // Greenify the collection based on the settings variable. return this.css({ color: settings.color, backgroundColor: settings.backgroundColor }); }; }( jQuery ));
对于默认参数,更标准的做法是建立一个$.fn.xxx.defaults变量,用来存放默认参数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Plugin definition. $.fn.hilight = function( options ) { // Extend our default options with those provided. // Note that the first argument to extend is an empty // object – this is to keep from overriding our "defaults" object. var opts = $.extend( {}, $.fn.hilight.defaults, options ); // Our plugin implementation code goes here. }; // Plugin defaults – added as a property on our plugin function. $.fn.hilight.defaults = { foreground: "red", background: "yellow" };
// Retain an internal reference: var wrapper = $( "<div />" ) .attr( settings.wrapperAttrs ) .appendTo( settings.container ); // Easy to reference later... wrapper.append( "..." );
1 2 3 4 5 6 7 8 9 10
var defaults = { wrapperAttrs : { class: "gallery-wrapper" }, // ... rest of settings ... }; // We can use the extend method to merge options/settings as usual: // But with the added first parameter of TRUE to signify a DEEP COPY: var settings = $.extend( true, {}, defaults, options );
如果用户还有修改元素样式的需求的话,还可以暴露css的控制权:
1 2 3 4 5 6 7 8 9 10
var defaults = { wrapperCSS: {}, // ... rest of settings ... }; // Later on in the plugin where we define the wrapper: var wrapper = $( "<div />" ) .attr( settings.wrapperAttrs ) .css( settings.wrapperCSS ) // ** Set CSS! .appendTo( settings.container );
var defaults = { // We define an empty anonymous function so that // we don't need to check its existence before calling it. onImageShow : function() {}, // ... rest of settings ... }; // Later on in the plugin: nextButton.on( "click", showNextImage ); function showNextImage() { // Returns reference to the next image node var image = getNextImage(); // Stuff to show the image here... // Here's the callback: settings.onImageShow.call( image ); }
这里,使用Function.prototype.call()来调用回调函数,是为了把回调函数的this设置为当前的image元素。这样在回调函数中直接使用$( this )就可以操作这个图片了:
1 2 3 4 5 6 7
$( "ul.imgs li" ).superGallery({ onImageShow: function() { $( this ).after( "<span>" + $( this ).attr( "longdesc" ) + "</span>" ); }, // ... other options ... });