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 插件和组件。
 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值