jQuery

封装我的jQuery

(function(){
    function jQuery(selector){
        return new jQuery.prototype.init(selector);
    }
    jQuery.prototype.init = function (selector){
        // 选出dom并且包装成jQuery对象 返回
        //id class
        this.length = 0;
        //null undefined dom
        if(selector == null){
            return this;
        }
        if(typeof selector == 'string' && selector.indexOf('.') != -1){
            var dom = document.getElementsByClassName(selector.slice(1));
        }else if(typeof selector == 'string' && selector.indexOf('#') != -1){
            var dom = document.getElementById(selector.slice(1))
        }
        if(selector instanceof Element || dom.length == undefined){
            this[0] = dom || selector;
            this.length++;
        }else{
            //基础铺垫
            for(var i = 0; i < dom.length; i ++){
                this[i] = dom[i];
                this.length++;
            }
        }
    }
    //入栈
    jQuery.prototype.pushStack = function (dom){
        if(dom.constructor != jQuery){
            dom = jQuery(dom)
        }else{
            dom.prevObject = this;
        }
        return dom;
    }
    
    jQuery.prototype.css = function(config){
        //循环操作每一个dom
        for(var i = 0; i < this.length; i ++){
            for(var attr in config){
                this[i].style[attr] = config[attr];
            }
        }  
        return this;
    }
    jQuery.prototype.get = function(num){
        return num != null ? (num >= 0 ? this[num] : this[num + this.length]) : [].slice.call(this, 0);
    }
    jQuery.prototype.eq = function(num){
        var dom = num != null ? (num >= 0 ? this[num] : this[num + this.length]) : null;
        return this.pushStack(dom)
    }

    jQuery.prototype.add = function(selector){
        var curObj = jQuery(selector);
        var baseObj = this;
        var newObj = jQuery();
        for( var i = 0; i < curObj.length; i ++){
            newObj[newObj.length++] = curObj[i];
        }
        for( var i = 0; i < baseObj.length; i ++){
            newObj[newObj.length++] = baseObj[i];
        }
        this.pushStack(newObj);
        return newObj;
    }
    jQuery.prototype.end = function(selector){
        return this.prevObject;
    }
    jQuery.prototype.init.prototype = jQuery.prototype;
    window.$ = window.jQuery = jQuery;
}());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值