一个最简朴的类JQuery封装

有时候在写一些演习或许小的项目时,我们能够只想用用jquery的$选择器,好用的hideshow等等一些基本的API,那末我们又不想由于这么几个API来引入一个jquery的js文件,那末本身封装一个最好不过了。

(function (document) {
    function DomObject(dom) {
        this.dom = dom;
    }

    function $(selector) {
        return new DomObject(document.querySelector(selector));
    }

    DomObject.prototype.get = function () {
        return this.dom;
    }

    DomObject.prototype.on = function(eventName, eventHandler) {
        this.get().addEventListener(eventName, eventHandler);
        return this;
    }

    DomObject.prototype.css = function(styleKey, styleValue) {
        this.get().style[styleKey] = styleValue;
        return this;
    };
    DomObject.prototype.hide = function() {
        this.get().style.display = 'none';
        return this;
    };
    DomObject.prototype.show = function() {
        this.get().style.display = 'block';
        return this;
    }

    $('.main #btn-hide').on('click', function() {
        $('h2').hide();
    });
    $('.container #btn-show').on('click', function() {
        $('h2').show().css('color','red');
    });
})(document);

起首建立一个组织函数,传入一个dom对象作为参数,在组织函数的原型对象上就能够绑定种种事宜,比方onshow以至是jquery中没有的css等等,假如想完成链式挪用,即返回this对象即可。应用querySelector来封装$,上面的示例只是简朴的封装,并没有完成兼容性的写法,比方on关于IE的处置惩罚。事宜侦听能够越发雄厚:通用的事宜侦听器只是关于jquery的完成道理举行的简朴的模仿。

简朴的封装一下,就能够兴奋的写东西啦。

    原文作者:海岛心hey
    原文地址: https://segmentfault.com/a/1190000008304292
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞