架子:

$(function () {
        var t1 = new Tab();
        ti.init('div1', {})
    })

    function Tab() {
        this.settings = { //默認參數
            event: 'click'
        }
    }
    Tab.prototype.init = function (_parent, opt) {
        $.extend(this.settings, opt);


    }

主要分離3方面:


配置參數:opt:events , delay


方法:methos:nowSel(),getContent


事件:beforeClick,afterClick


注意的點:

1、jq中主動解發 $(_this).trigger('afterClick'),相當於 autoEvent(_this, 'afterClick') ;


2、特別留意this指向問題;


3、jq中$.extend(this.settings, opt),相當於 extend(this.settings, opt)


    $(function () {
        var t1 = new Tab();
        t1.init('div1', {})
        var t2 = new Tab();
        t2.init('div2', {
            event:'mouseover'
        })

        var t3 = new Tab();
        t3.init('div3', {
            event:'mouseover',
            delay:200
        })
        var t4 = new Tab();
        t4.init('div4', {})
        t4.nowSel(2)
        $('#inp1').click(function(){
            console.log(t4.getContent());
        })

        $(t4).on('beforeClick', function () {
            console.log(t4.getContent() + ' before');
        })
        $(t4).on('afterClick', function () {
            console.log(t4.getContent() + ' after');
        })

    })

    function Tab() {
        this._parent = null;
        this._inp = null;
        this._div = null;
        this.cur = 0;
        this.settings = { //默認參數
            event: 'click',
            delay:0
        }
    }
    Tab.prototype.init = function (_parent, opt) {
        $.extend(this.settings, opt);
        this._parent = $('#'+_parent);
        this._inp = this._parent.find('input');
        this._div = this._parent.find('div');
        this.change();
    }
    Tab.prototype.change = function () {
        var _this = this;
        var _t = null;
        this._inp.on(this.settings.event,function(){

            var This = this;
            if(_this.settings.event == 'mouseover' && _this.settings.delay){
                _t = setTimeout(function(){
                    show(This)
                },_this.settings.delay);
            }
            else{
                show(this)
            }
        }).mouseout(function () {
            clearTimeout(_t);
        })
        function show(obj){ //obj指按鈕;

            $(_this).trigger('beforeClick') ; //點擊前

            $(obj).attr('class','active').siblings().removeClass('active');
            _this._div.eq($(obj).index()).css('display','block').siblings('div').css('display','none')
            _this.cur = $(obj).index()  //千萬注意this指向,坑

            $(_this).trigger('afterClick') ; //點擊前
        }
    }
    Tab.prototype.nowSel = function(index){
        this._inp.eq(index).attr('class','active').siblings().removeClass('active');
        this._div.eq(index).css('display','block').siblings('div').css('display','none')
        this.cur = index;
    }
    Tab.prototype.getContent = function () {
        return this._div.eq(this.cur).html()
    }

http://tangram.baidu.com/magic/