jQuery插件总结

jQuery插件小结
编写jQuery插件,是从添加一个新的函数属性到jQuery.fn对象开始的,其中新的函数属性名为你要编写插件的名称:
jQuery.fn.myPlugin = function() {
  // Do your awesome plugin stuff here
};
<!--[if ppt]--><!--[endif]-->
然而为了确保你的插件不会与其他可能使用$符号的javascript库冲突,将jQuery对象当做参数传递到一个可立即执行的函数表达式中(IIFE),该函数表达式会通过$符号来映射jQuery对象,这样在该函数表达式内,$符号将不会被在其可执行的作用域中的其他库所覆盖。
(function( $ ) {
  $.fn.myPlugin = function() {
   // Do your awesome plugin stuff here };

   })( jQuery );

 

编写一个实现了一些功能的插件。
(function( $ ){
   $.fn.maxHeight = function() {
   var max = 0;
  this.each(function() {
  max = Math.max( max, $(this).height() );
     });
   return max;
   };
})( jQuery );
var tallest = $('div').maxHeight();

 

通过调用 .height() 来获取页面最高div元素的高度。
 
包含可选项的复杂可定制化插件,增加能在被调用时可扩展(使用$.extend)的默认设置。避免在调用插件时传递大量参数,在调用时使用一个需要覆盖掉的参数对象。如下
(function( $ ){
  $.fn.tooltip = function( options ) {
  var settings = $.extend( {
     'location' : 'top',
  'background-color' : 'blue'
  }, options);  
  return this.each(function() {
  });
   };
})( jQuery );
$('div').tooltip({ 'location' : 'left' });
当使用给定的可选项调用 tooltip 插件方法后,默认的 'location' 属性会被设置成 'left', 'background-color' 属性则保持不变。
 
个单独的插件在jQuery.fn对象上的命名空间都不应超过一个
应该将所有插件的方法存放在一个对象字面量中,然后通过传递方法的字符串名称来调用。
(function( $ ){
  var methods = {
   init : function( options ) { //   },
   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 );
$('div').tooltip();
$('div').tooltip({ foo : 'bar' });
$('div').tooltip('hide');
$('div').tooltip('update', 'This is the new tooltip content!');
通过先传递方法的字符串名称,再传递其他一些这个方法可能用到的参数来调用。这种方式的方法封装和架构在jQuery插件社区是一种标准并被无数的插件采用,包括jQuyerUI插件和组件。