美文网首页
小试牛刀,JavaScript原型链实现JQuery代码!

小试牛刀,JavaScript原型链实现JQuery代码!

作者: LeeYaMaster | 来源:发表于2019-04-28 15:32 被阅读0次

这个项目是采用JS的原型链写出来的,原理是,每次$(),触发原型链的构造方法,根据第一位的符号,来判断document.getElementById还是Class还是Tag。通过这样来获取对象,再来使用功能的方法,来达到JQuery的效果,先来看代码吧。
核心代码:

  (function() {//采用(function(){})();不让外面的变量干扰里面,最后用window导出。
    var jquery = function(param) {//构造方法,每次都会调用它的init方法。
        return new jquery.prototype.init(param);//调用init方法
    }
     //方法类
    jquery.prototype = {//让jquery对象,实现一个原型链,给他添加上方法。
        init: function(param) {//每次$()都会调用这个方法,然后根据它的值,返回一个DOM对象。
            var param = param.trim();//去除空格
            var mark = param.charAt(0);//获取第一个字符。
            if(mark == "#") {//根据值,再去获取DOM对象,有三种,id,class,tagName(元素名)
                this[0] = document.getElementById(param.substring(1)); //获取
            } else if(mark == ".") {
                this[0] = document.getElementsByClassName(param.substring(1));
            } else {
                this[0] = document.getElementsByTagName(param);
            }
            console.log(this);//是一个基于jquery(自己命名的)的对象,打印出来。
            console.log(this[0]);//是jquery对象的第一个值,也就是元素的DOM对象。
            return this;//返回一个JQuery对象。
        },  
        //下面写自己的方法。
        css: function() {
           
        },
        jquery.ajax = function(){
            console.log("进入ajax方法")
        }
   }

    jquery.prototype.init.prototype = jquery.prototype; //把jq的原型赋值给init的原型,这样就不用每次都new了。
    window.$ = window.jquery = jquery;//让外部可以访问,之后外部可以通过$()来触发构造函数。
})();
(function() {
    var jquery = function(param) {
        return new jquery.prototype.init(param);
    }

    //方法类
    jquery.prototype = {
        init: function(param) {
            var param = param.trim();
            var mark = param.charAt(0);
            if(mark == "#") {
                this[0] = document.getElementById(param.substring(1)); //获取
            } else if(mark == ".") {
                this[0] = document.getElementsByClassName(param.substring(1));
                console.log(this[0]);
                console.log(this);
            } else {
                this[0] = document.getElementsByTagName(param);
            }
            return this;
        },  
        
        //添加css成功
        css: function() {
            if(arguments.length % 2 != 0) {
                console.log('请输入偶数的参数');
                return false;
            }
            for(var i = 0; i <= arguments.length; i += 2) {
                this[0].style[arguments[i]] = arguments[i + 1];
            }
        },

        //添加class成功
        addClass: function(sclass) {
            for(var i = 0; i < arguments.length; i++) {
                this[0].classList.add(arguments[i]);
            }
        },

        //删除class单个样式成功
        removeClass: function(sclass) {
            this[0].classList.remove(sclass);
        },
        //添加attr单个属性成功
        attr: function(sname, sval) {
            this[0].setAttribute[sname] = sval;
        },

        //获取单个父元素成功
        parent: function() {
            this[0] = this[0].parentElement;
            return this;
        },

        //获取所有下一级的子元素
        children: function(num) {
            if(num == null){
                this[0] = this[0].children;
                console.log(this);
                return this;
            }else{
                this[0] = this[0].children[num];
                console.log(this);
                return this;
            }
        },
        
        //设置表单的值成功(成功)
        val: function(arguments) {
            if(arguments == null){
                return this[0].value;
            }else{
                return this[0].value = arguments;
            }
        },
        //转换为html代码成功(成功)
        html: function(arguments) {
            if(arguments == null){
                console.log(this[0].innerHTML);
                return this[0].innerHTML = null;
            }else{
                console.log(this[0].innerHTML)
                return this[0].innerHTML = arguments;
            }
        },
        //获取文本值成功(成功)
        text: function(arguments) {
            if(arguments == null){
                return this[0].innerText;
            }else{
                return this[0].innerText = arguments;
            }
        },
        //前面追加节点成功
        prepend : function(arguments){
            return this[0].innerHTML = arguments + this[0].innerHTML;
        },
        //后面追加节点成功
        append: function(arguments) {
            //因为appendChild方法,追加节点必须创建一个对象,所以我这里,用的innerHTML方法。
            //var para = document.createElement(arguments);
            //return this[0].appendChild(para);
            return this[0].innerHTML += arguments;
        },
        get: function(url,fn) {
            // XMLHttpRequest对象用于在后台与服务器交换数据   
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.onreadystatechange = function() {
                // readyState == 4说明请求已完成
                if(xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) {
                    // 从服务器获得数据 
                    fn.call(this, xhr.responseText);
                    console.log(xhr.responseText);
                }
            };
            xhr.send();
        },
        // datat应为'a=a1&b=b1'这种字符串格式,在jq里如果data为对象会自动将对象转成这种字符串格式
        post: function(url, data, fn) {
            var xhr = new XMLHttpRequest();
            xhr.open("POST", url, true);
            // 添加http头,发送信息至服务器时内容编码类型
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.onreadystatechange = function() {
                if(xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
                    fn.call(this, xhr.responseText);
                }
            };
            xhr.send(data);
        },
        ajax: function() {

        },
        
        //淡入成功
        show: function(time = 200) {
            var num = 0;
            this[0].style.display = "block";
            this[0].style.opacity = num;
            var st = setInterval(()=>{
                num++;
                this[0].style.opacity = num / 10;
                if(num >= 10) {
                    clearInterval(st);
                }
            }, time)
        },
        //淡出成功
        hide: function(time = 200){
            var num = 10;
            var st = setInterval(()=>{
                num --;
                this[0].style.opacity = num/10;
                if(num<=0){
                    clearInterval(st);
                }
            },time)
        },
        //移入事件成功
        onmouseover: function(fun){
            this[0].onmouseover = fun;
            //console.log(this[0].childNodes);//不让子节点有移入方法
            /*for(var i=0;i<this[0].childNodes.length;i++){
                this[0].childNodes[i].onmouseover = null;
            }*/
            return this;
        },
        //移出事件成功
        onmouseout : function(fun){
            this[0].onmouseout = fun;
            return this;
        },
        //移入移出事件成功
        hover: function(fun1,fun2){
            this[0].onmouseover = fun1;
            this[0].onmouseout = fun2;
            return this;
        },
        //toggleClass添加删除成功
        toggleClass: function(sclass){
            console.log(arguments);
            for(var i = 0; i < arguments.length; i++) {
                if(this[0].classList.contains(arguments[i])){
                    this[0].classList.remove(arguments[i]);
                }else{
                    this[0].classList.add(arguments[i]);
                }
            }
        },

        //点击事件成功
        onclick : function(fun){
            this[0].onclick = fun;
            return this;
        },
        //双击事件成功
        ondblclick : function(fun){
            this[0].ondblclick = fun;
            return this;
        },
        //鼠标释放事件成功
        onmouseup : function(fun){
            this[0].onmouseup = fun;
            return this;
        },
        //光标聚集事件成功
        onfocus : function(fun){
            this[0].onfocus = fun;
            return this;
        },
        //失焦事件事件成功
        onblur : function(fun){
            this[0].onblur = fun;
            return this;
        },
        //内容选中事件
        onselect : function(fun){
            this[0].onselect = fun;
            return this;
        },
        //文本框内容改变事件
        onchange : function(fun){
            this[0].onchange = fun;
            return this;
        },
        //加载事件
        onload : function(fun){
            this[0].onload = fun;
            return this;
        },
        //卸载事件
        onunload : function(fun){
            this[0].onunload = fun;
            return this;
        },
        //设置高度成功
        height : function(arguments){
            if(arguments == null){
                return this[0].clientHeight;
            }else{
                return this[0].clientHeight = arguments; 
            }
        },
        //设置宽度成功
        width : function(arguments){
            if(arguments == null){
                return this[0].clientWidth;
            }else{
                return this[0].clientWidth = arguments; 
            }
        },
    }

    jquery.prototype.init.prototype = jquery.prototype; //把jq的原型赋值给init的原型
    window.$ = window.jquery = jquery;
})();

HTML代码没啥用,就是测试用的。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .bg-info {
                background-color: #d9edf7;
            }
            
            .btn-lg {
                padding: 10px 16px;
                font-size: 18px;
                line-height: 1.3333333;
                border-radius: 6px;
            }
            
            .bg-danger {
                background-color: #f2dede;
            }
            
            .text-center {
                text-align: center;
            }
            
            #main{
                width: 200px;height: 100px;
            }
            .testMain{
                width: 300px;
                height: 300px;
            }
            .testBule{
                background-color: #D9EDF7;
            }
        </style>
    </head>
    <body id="body" class="body">
        <button class="btn-lg" onclick="test()">测试</button>
        <div id="main" class="bg-info">
            <p class="text-center bg-danger">测试的文字</p>
        </div>
        <script type="text/javascript" src="js/MyJQuery.js" ></script>
        <script>
            function test() {
                //$('#main').toggleClass('testMain', 'testMain');//成功
                //$('#main').css('color','#00FF00');
                //$('#main').addClass('testMain','testMain');
                //$('#main').html('1234');
                //$('#main').parent().css('color','#00FF00','text-align','center');
                //$('#main').html('1234');
                //$('#main').text('1');
                //$('#main').append('<h1>啊哈</h1>');
                //$('#main').children(1).css('color','#00FF00','text-align','center');
                /*ajax:function(){
                    url: 'www.baidu.com/getInfo',
                    type :'POST',
                    data: {
                        name: 'jack',
                        age: 18
                    },
                    dataType: 'json',
                    success: function(resp){
                    // callback
                    },
                    error: function(err){
                    // error code
                    } 
                },*/
                //$('#main').get('https://www.runoob.com/try/ajax/ajax_info.txt');
                //$('#main').append('<h1>aaa</h1>');
                //$('#main').prepend('<h1>aaa</h1>');
                //$('#main').html();
                //$('#main').hide();//切换为显示完成
                //$('#main').height();//获取高度成功
                //$('#main').width();//获取宽度成功
                /*$("#main").onmouseover(function () {
                    console.log('正在执行移入');
                }).onmouseout(function(){
                    console.log('正在执行移出');
                }).onclick(function(){
                    console.log('正在执行点击');
                }).ondblclick(function(){
                    console.log('正在执行鼠标双击事件');
                }).onmouseup(function(){
                    console.log('正在执行鼠标释放');
                });*/
            }
        </script>
    </body>
</html>

首先这个项目还不完整,还有问题需要修改:
1:ajax跨域,我在本地是用nginx反向代理实现的,作为一个框架,应该要改成jsonp来实现。
2:这项目是半年前我写的项目,那时候我刚开始学ES6,像这种原型链的项目,用ES6面向对象来解决,是最好不过的了,在2.0版本,我将用TypeScript或者ECMAScript6来实现一下。

目前这个项目还在完善,肯定会有不足的地方,请多指教,希望提出你们宝贵的建议,来让这个项目更加完美!

相关文章

网友评论

      本文标题:小试牛刀,JavaScript原型链实现JQuery代码!

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