JavaScript - 封装简单版 jQuery

  • 模块化
(function(){
    ......            
})()
  • 声明一个 jQuery 函数
(function(){
    // 声明一个 jQuery函数
    function jQuery(){
                
    }

    // 给 window 对象添加一个 jQuery 函数
    window.$ = window.jQuery = jQuery;
})()
  • 实现功能:$("div").css("color", "red")
(function() {
    function jQuery(selector) {
        return new jQuery.prototype.init(selector);
    }

    window.$ = window.jQuery = jQuery;

    jQuery.prototype = {
        constructor:jQuery,
        init:function(selector) {
            var elements = document.querySelectorAll(selector);
                
            for (var i=0; i<elements.length; i++) {
                this[i] = elements[i];
            }

            this.length = elements.length;
        }
    }

    jQuery.prototype.init.prototype = {
        constructor:jQuery.prototype.init,
        css:function(name, value) {
            for (var i=0; i<this.length; i++) {
                this[i].style[name] = value;
            }
        }
    }
})()

  • 测试
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div>1</div>
    <div>2</div>
    <div>3</div>

    <script>
        (function() {
            function jQuery(selector) {
                return new jQuery.prototype.init(selector);
            }

            window.$ = window.jQuery = jQuery;

            jQuery.prototype = {
                constructor:jQuery,
                init:function(selector) {
                    var elements = document.querySelectorAll(selector);
                
                    for (var i=0; i<elements.length; i++) {
                        this[i] = elements[i];
                    }

                    this.length = elements.length;
                }
            }

            jQuery.prototype.init.prototype = {
                constructor:jQuery.prototype.init,
                css:function(name, value) {
                    for (var i=0; i<this.length; i++) {
                        this[i].style[name] = value;
                    }
                }
            }
        })()

        $("div").css('color', 'red');
    </script>
</body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 28,401评论 1 45
  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 13,162评论 0 3
  • 一.什么是jQuery jQuery是一个JavaScript库,它通过封装原生的JavaScript函数得到一整...
    love2013阅读 3,685评论 0 4
  • 请参看我github中的wiki,不定期更新。https://github.com/ivonzhang/Front...
    zhangivon阅读 12,201评论 2 19
  • 前端开发面试题 面试题目: 根据你的等级和职位的变化,入门级到专家级,广度和深度都会有所增加。 题目类型: 理论知...
    怡宝丶阅读 7,408评论 0 7

友情链接更多精彩内容