• 原生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","我的图片"));
  • 相关阅读:
    [转]find高级用法
    svn服务器配置
    awk (一)
    Linux下恢复ext3文件系统误删除文件ext3grep
    cobbler无人值守安装操作系统
    Linux下virtualbox网络配置
    nginx+uwsgi来部署Django
    solaris 网络设置
    rpm 使用说明
    linux 下安装mysql
  • 原文地址:https://www.cnblogs.com/xiaohaoxuezhang/p/4838499.html
Copyright © 2020-2023  润新知