zoukankan      html  css  js  c++  java
  • 原生JS实现jquery的链式编程。

    这是我根据之前遇到的一个面试题,题目:用原生JS实现$("#ct").on("click",fn).attr("id")。

    然后看了篇jquery源码分析(http://www.cnblogs.com/aaronjs/p/3279314.html),自己写出来的一个实现,选择器用的querySelector,关于链式编程也只是返回this而已,这也算是自己看jquery源码解决的第一个问题吧,继续加油。

    现在想来当年面试官确实没说错,我jquery基础确实差,慢慢学吧,要学的还在很多。

    先上代码吧。

     var jq = function(selector){
               return new jq.prototype.init(selector);
           };
            jq.prototype = {
                init:function(selector){
                    this.el = document.querySelector(selector);
                    return this;
                },
                on:function(event,fn){
                    if(window.addEventListener){
                        this.el.addEventListener(event,fn,false);
                    }else if(window.attachEvent){
                        this.el.attachEvent(on+event,fn);
                    }
                    return this;
                },
                attr:function(event,val){
                    if(!val){
                        return this.el.getAttribute(event);
                    }else{
                        this.el.setAttribute(event,val);
                        return this;
                    }
                }
            }
            jq.prototype.init.prototype = jq.prototype;
    
            console.log(jq("#ct").on("click",function(){alert("您点击了我。")}).attr("title","我的图片"));
  • 相关阅读:
    Markdown 语法说明 (简体中文版)
    Markdown Reference
    BZOJ 2229 最小割
    BZOJ 3569 DZY Loves Chinese II
    BZOJ 3563 DZY Loves Chinese
    BZOJ 2956 模积和
    BZOJ 2957 楼房重建
    查漏补缺:面向对象设计原则
    添砖加瓦:设计模式(简单工厂模式)
    添砖加瓦:设计模式(总述)
  • 原文地址:https://www.cnblogs.com/xiaohaoxuezhang/p/4838499.html
Copyright © 2011-2022 走看看