美文网首页
JQuery链式调用的实现

JQuery链式调用的实现

作者: 也在水湄 | 来源:发表于2019-07-10 10:20 被阅读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")
    

    相关文章

      网友评论

          本文标题:JQuery链式调用的实现

          本文链接:https://www.haomeiwen.com/subject/zmjckctx.html