JQuery链式调用的实现

JQuery链式调用的实现


        function jQuery(selector) {
            this.selector = document.querySelector(selector);
        }

        function $(selector) {
            return new jQuery(selector);
        }

        jQuery.prototype.hover = function (enterfn, leavefn) {
            this.selector.onmouseenter = enterfn;
            this.selector.onmouseleave = leavefn;
            return this;
        }


        jQuery.prototype.click = function (callback) {
            this.selector.onclick = callback;
            return this;
        }

        jQuery.prototype.addClass = function (cName) {
            var isClass = this.selector.getAttribute("class");
            console.log(isClass);
            if (isClass != null) {
                if (isClass.indexOf(cName) != -1) { return; }
                var arr = isClass.split(" ");
                arr.push(cName);
                newStr = arr.join(" ");
                this.selector.className = newStr;
            }
            this.selector.className = cName;
            return this;
        }
  
        //链式调用
        $("#box").hover(function () {
            this.style.background = "red";
        }, function () {
            this.style.background = "skyblue";
        }).click(function () {
            this.style.border = "1px solid #000"
        }).addClass("boxShadow")
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。