// tabs.js文件整体代码如下:
(function($) { 'user strict'; var Tab=function(config) { this.init(config); }; Tab.prototype={ constructor:Tab, //初始化属性和事件 init:function(config) { this.menuId=config.menuId||'tab-menu'; this.mainId=config.mainId||'tab-main'; this.$menu=$('#'+this.menuId).children(); this.$main=$('#'+this.mainId).children(); //维护一个index this.index=0; this.isAuto=config.isAuto||false; this.isAuto && this.autoPlay(); this.initEvent(); }, //单一职责:每个方法尽可能的单一 //抽离方法:绑定事件 , 实现tab切换 initEvent:function() { var that=this; this.$menu.on('click',function(){ //此处函数的this指向当前dom对象 that.index= $(this).index(); that.change(); }); }, //切换功能 change:function() { //此处的this是当前的实例对象 //var index= $(this).index(); this.$menu.eq(this.index).addClass('active').siblings().removeClass('active'); this.$main.eq(this.index).addClass('selected').siblings().removeClass('selected') }, //自动轮播功能 autoPlay:function() { var that=this; var set=function() { that.index++; if(that.index>3){ that.index=0; } that.change(); }; //清理计时器 var setId=setInterval(set,1000); this.$menu.mouseenter(function() { clearInterval(setId) }).mouseleave(function() { setId=setInterval(set,1000); }); }, //下一张功能 playNext:function() { this.index++; if(this.index>3){ this.index=0; } this.change(); }, //上一张功能 playPrve:function() { this.index--; if(this.index<0){ this.index=3; } this.change(); } }; //暴露在全局中 $.fn.tab=function(config) { //原型this是jQuery对象 new Tab(config); } })(jQuery)利用沙箱模式传入jQuery / $, 将 fn 作为jQuery中全局变量$的属性即可; //保证全局环境中只声明了一个变量 jQuery / $ , 将全局污染最小化; 最终最终,我们只需要引入文件,像jQuery一样调用时传入父元素id即可; <script src="js/jquery.js"></script> <script src="js/tabs.js"></script> <script type="text/javascript"> $('#wrapper').tab({ isAuto:true }); </script> html结构就省略了,根据代码结构自行脑补吧个人日记 , 纯手打 ,欢迎指正 !