JQuery链式调用的实现

2019-07-10  本文已影响0人  也在水湄

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")
上一篇下一篇

猜你喜欢

热点阅读